我的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);
}
答案 0 :(得分:0)
由于JPanel
扩展了Component
,因此可以使用Component#setName(String)
进行命名。我会给gamePanel一个自定义名称,以便它可以在数组中识别。对于eaxmple,您的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();
}
}));
如果你不能使用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
参数,并将您的游戏面板传递给该参数:
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);
}