2013-12-09 3 views
1

숙제 지정을위한 도움말을 다시 찾습니다. 나는 이것을 거의 가지고 있지만, for-loop가 사용자 텍스트 입력을 기다릴 수없는 이유를 이해하는 데 어려움을 겪고있다. 기본적으로, 나는 암기에서 색깔을 입력하도록 사용자를 자극하는 프로그램이 필요합니다. 색상은 배열에 문자열로 포함됩니다. for-loop를 반복 할 때마다 액션 리스너가 적절한 텍스트가 입력되었는지 확인하고 확인하고 싶습니다. 그렇다면 상자의 JLabel 텍스트가 "색상 번호 x를 입력하십시오."에서 "색상 번호 x + 1을 입력하십시오"로 바뀌어야합니다.For 루프가 JTextField에서 사용자 응답을 기다리지 않습니다.

여기에 제가 눈치 챘을 겁니다 : My 반복문은 전체 반복주기 사용자가 필드에 텍스트를 입력하게합니다. 그래서 그 대신 색상 번호 1의 사용자에게 메시지를 표시의, 그냥 색상 번호 해협 간다 5.

여기에 내가 그것을 가지고 코드입니다 :

import javax.swing.*; 
import java.awt.*; 
import java.util.*; 
import java.awt.event.*; 

public class ColorGame extends JFrame 
{ 
    private static final int WIDTH = 300; 
    private static final int HEIGHT = 200; 
    //Text field that will confirm a user submission 
    private JTextField colorEntry = new JTextField(10); 
    private int colorIndex = 0; //current index of colorSequence 
    //String Array of colors to be searched for and validated in a text field 
    private String[] colorSequence = {"red", "white", "yellow", "green", "blue"}; 

    public ColorGame() 
    { 
    setTitle("Memory Game"); 
    setSize(WIDTH, HEIGHT); 
    setLayout(new FlowLayout()); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    createContents(); 
    setVisible(true); 
    } 

    public void createContents() 
    { 
    //dialog box to inform user of program's purpose 
    JOptionPane.showMessageDialog(null, "How good is your memory?\nTry to memorize " 
     + "this color sequence:\n\nred, white, yellow, green, blue"); 
    //JLabel to prompt user for color 
    JLabel colorPrompt = new JLabel(); 

    add(colorPrompt); 
    add(colorEntry); 

    for(int i = 0; i < colorSequence.length; i++) 
    { 
     colorIndex = i + 1; 
     colorPrompt.setText("Enter color number " + colorIndex + ":"); 
     colorEntry.addActionListener(new Listener()); 
    } 
    } 

    private class Listener implements ActionListener 
    { 
    public void actionPerformed(ActionEvent e) 
    { 
     String colorText = ""; 

     colorText = colorEntry.getText(); 
     if(colorText.equals(colorSequence)) 
     System.out.println("Hello"); 
     else 
     System.out.println("No"); 

    } 
    } 

    public static void main(String[] args) 
    { 
    new ColorGame(); 
    } 
} 

답변

0

을, 나는 반복 할 필요가 없습니다 것을 알아내는 결국 createContents() 내 작업 및 내 작업이 수신기를 통해 반복되는. 이벤트 중심 프로그래밍에 대한 귀하의 의견은 저를 도왔습니다.

private class Listener implements ActionListener 
{ 
    //counter to dynamically change numeric text values 
    //as well as to mark progress through colorSequence 
    int count = 1; 
    public void actionPerformed(ActionEvent e) 
    { 
    if (count < colorSequence.length) 
    { 
     if (colorEntry.getText().equals(colorSequence[count - 1])) 
     { 
     count++; 
     colorEntry.setText(""); 
     colorPrompt.setText("Enter color number: " + count); 
     } 
     else 
     { 
     colorEntry.setVisible(false); 
     colorPrompt.setText("Sorry - wrong answer. Eat more antioxidants."); 
     } 
    } //end if (for while the program is still iterating through the array) 
    else 
    { 
     colorPrompt.setText("Congratulations - your memory is perfect"); 
     colorEntry.setVisible(false); 
    } //end else (the user has properly stepped through all the colors in the array) 
    } //end actionPerformed 
} //end private class Listener 
2

귀하의 루프는은 줄에 대한 코드입니다 by-line run 명령 행 프로그램이지만, GUI를 사용하여 이벤트를 주도하는 방식이 아닙니다.

대신 ActionListener의 코드에서 카운터를 진행하고 해당 카운터를 기반으로 동작을 변경해야합니다.

private class Listener implements ActionListener 
{ 

    int counter = 0; 
    public void actionPerformed(ActionEvent e) 
    { 
    switch (count) { 
     case 0: 
     // do something for 0 
     // including changing JLabel text if need be 
     break;    
     case 1: 
     // do something for 1 
     break; 
     case 2: 
     // do something for 2 
     break; 
     default; 
     // do something for default 
    } 
    count++; 

    } 
} 

for 루프는 사용자 입력이나 버튼을 눌러도 걱정할 필요없이 즉시 루프됩니다. 핵심은 프로그램의 상태를으로 변경하려는 경우 JButton이 눌려진 횟수에 따라 다릅니다. 그리고 상태 변경은 버튼 누름에 의해 트리거되기 때문에 너무 빠르게 루프 루핑하는 것에 대해 걱정할 필요가 없습니다. 여기


은 정확한 솔루션이 아닌 관련 예,하지만 당신에게 당신의 솔루션을 향해 몇 가지 아이디어 제공한다 : 기본적으로

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;  
import javax.swing.*; 

public class ChangeState { 

    public static final String[] STRINGS = { 
     "Enter the 1st String:", 
     "Enter the 2nd String:", 
     "Enter the 3rd String:" 
    }; 

    private static void createAndShowGui() { 
     final JTextField textField = new JTextField(10); 
     final String[] replies = new String[STRINGS.length]; 
     final JLabel label = new JLabel(STRINGS[0]); 
     JPanel mainPanel = new JPanel(); 
     mainPanel.add(label); 
     mainPanel.add(textField); 

     textField.addActionListener(new ActionListener() { 
     int count = 0; 
     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      if (count < STRINGS.length) { 
       replies[count] = textField.getText(); 
       count++; 
       if (count < STRINGS.length) { 
        label.setText(STRINGS[count]); 
       } else { 
        label.setText("Done!"); 
        System.out.println("Replies:"); 
        for (String reply : replies) { 
        System.out.println(reply); 
        } 
       } 
       textField.setText(""); 
      } 
     } 
     }); 

     JFrame frame = new JFrame("ChangeState"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+0

그래서 내 createContents 메서드의 for-loop 대신 Listener 메서드에서 for-loop를 사용하고 싶습니다. –

+0

@ZachFiedler : ** No **, 이벤트 구동 프로그래밍의 상태를 변경하는 방식이 아니기 때문에 for 루프 * 아무 곳이나 사용하지 않을 것입니다. 위의 답변을 수정하십시오. –

+0

나는 Java에 대해 매우 신선하다는 사실을이 머리말에 두어야한다. 귀하의 코드는 매우 유용했습니다! 액션 리스너 내부에서 if 문을 논리적으로 사용하여 정보를 지속적으로 업데이트하고 숫자 프롬프트를 동적으로 변경하는 방법을 찾아 냈습니다. –

관련 문제