0

Stringaを anに渡すことは可能ActionListenerですか? 数当てゲームを作成していますが、選択した難易度を に渡す必要がありActionListenerます。これは、最初に開いた GUI から渡されるためです。コンストラクターに直接渡されるので、これをどのように行うのGame()ですか?

4

4 に答える 4

0

Have your ActionListener access a variable that contains the result of the guess.

I would do something like:

    final JTextArea textArea = new JTextArea();
    JButton button =new JButton("press");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            String text = textArea.getText();
            if (text.equals("something")) {
                doSomething();
            } else {
                doSomethingElse();
            }
        }
    });
于 2012-05-27T05:52:48.937 に答える
0

文字列はどこから来たのですか?そのコンポーネントをActionListener構築時に渡すことができます。たとえば、文字列はJLabelオブジェクトから取得されます。それで

class GuessNumberActionListener implements ActionListener {
    private JLabel difficulty;

    public GuessNumberActionListener(JLabel difficulty) {
        this.difficulty = difficulty;
    }

    // implement other methods
}

次に、アクションリスナー内で、必要なものにアクセス/更新できます。

于 2012-05-27T05:54:15.370 に答える
0

ActionListener はインターフェースです。継承を使用してインターフェイスの機能を拡張してみてください。これはトリックを行います

于 2012-05-27T05:56:25.507 に答える
-1

Sure you can. There are lots of ways but one of them is to pass it in to the the ActionListener's constructor:

public class MyClass implements ActionListener { 

    private int difficultyLevel;

    public MyClass(int difficultyLevel) {
      this.difficultyLevel = difficultyLevel;
    }

    public void actionPerformed(ActionEvent e) { 
        ...//code that reacts to action and does something based on difficultyLevel
    }

}

UPDATE:

Looks like the design patterns police are out in full force today. You may want to quickly rewrite your app in MVC before you get shot in the foot :)

http://java.sun.com/products/jfc/tsc/articles/architecture/

于 2012-05-27T05:52:37.970 に答える