繁体   English   中英

java对动作侦听器中的类的引用

[英]java reference to class in action listener

我有 JPanel,里面包含另外两个 JPanel,gamePanel 和 OptionsPanel。 我希望 OptionsPanel 包含一个按钮,该按钮将在单击时触发 gamePanel 方法。 有没有比仅仅引用对象本身更好的方法来做到这一点? (接下来我想做op.getParent.getComponents()

class OptionsPanel extends JPanel{
OptionsPanel op = this;

public OptionsPanel(){
    JButton start = new JButton("Rozwiąż sudoku");
    start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //some code to do
        }
    });
    this.add(start);
}
}

这是一个包含 gamePanel 和 OptionsPanel 的类的片段

public Sudoku () {
    Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setPreferredSize( new Dimension(1000,550) );

    GamePanel gamePanel = new GamePanel();
    this.gamePanel = gamePanel;

    OptionsPanel optionsPanel = new OptionsPanel();
    this.optionsPanel = optionsPanel;

    add(gamePanel);
    add(optionsPanel);
}

爪哇 8


因为JPanel扩展了Component ,它可以使用Component#setName(String)命名。 我会给 gamePanel 一个自定义名称,以便它可以在数组中识别。 例如,您的 gamePanel 构造函数可能如下所示:

public GamePanel() {
    this.setName("gamePanel");
}

你可以用这个名字把它挑出来:

start.addActionListener(e -> java.util.Arrays.stream(op.getComponents()).forEach(c -> {
    if (c.getName().equals("gamePanel")) {
        ((GamePanel) c).method();
    }
}));

爪哇 7


如果您不能使用Stream API 或 lambda 表达式,您可以简单地使用 for 循环:

start.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < op.getComponentCount(); i++) {
            Component c = op.getComponent(i);
            if (c.getName().equals("gamePanel")) {
                ((GamePanel) c).method();
            }
        }
    }
});

其他


还有另一种方法,效率更高,混乱程度更低。 你可以包括GamePanel在参数OptionsPanel的构造和你的GamePanel传递到:

public OptionsPanel(GamePanel gamePanel){
    JButton start = new JButton("Rozwiąż sudoku");
    start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            gamePanel.method();
        }
    });
    this.add(start);
}

然后你需要做的就是改变你构造 optionsPanel 实例的方式:

public Sudoku () {
    Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setPreferredSize( new Dimension(1000,550) );

    GamePanel gamePanel = new GamePanel();
    this.gamePanel = gamePanel;

    // Pass your GamePanel instance to the constructor.
    OptionsPanel optionsPanel = new OptionsPanel(gamePanel);
    this.optionsPanel = optionsPanel;

    add(gamePanel);
    add(optionsPanel);
}

暂无
暂无

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

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