繁体   English   中英

传递给听众

[英]Passing to listener

是否可以将String传递给ActionListener 我正在创建一个猜数字游戏,我需要将选择的难度传递给ActionListener ,因为它是从打开的第一个GUI传递过来的。 将其直接传递给Game()构造函数时,我将如何处理?

让您的ActionListener访问一个包含猜测结果的变量。

我会做类似的事情:

    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();
            }
        }
    });

字符串从哪里来? 您可以在构造时将该组件传递给ActionListener 例如,您的字符串来自JLabel对象。 然后

class GuessNumberActionListener implements ActionListener {
    private JLabel difficulty;

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

    // implement other methods
}

然后在动作监听器中,您可以访问/更新所需的内容。

ActionListener是一个接口。 尝试使用继承扩展接口的功能。 这将达到目的

你当然可以。 有很多方法,但是其中一种是将其传递给ActionListener的构造函数:

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
    }

}

更新:

看起来警察今天已经全力以赴使用设计模式了。 您可能需要在MVC中快速重写您的应用,然后再开始尝试:)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM