我正在制作一款棋盘游戏。一个类包含主 UI(保存、加载、标签等),另一类包含实际的棋盘游戏按钮(8x8 按钮数组)。
我希望第一类等待,直到按下第二类中的所有按钮,然后继续执行该程序。
这是我应该用线程来解决的问题吗?如果是这样,请有人给我指明正确的方向。
更新
MCVE:
public class MyGUI {
JFrame frame;
Panel mainPanel;
Panel boardPanel;
createGUI () {
frame = new JFrame();
mainPanel = new Panel();
boardPanel = new Panel();
frame.add(mainPanel);
}
addBoard () {
Board board = new Board(boardPanel);
frame.setVisibile(true);
}
}
----------------------------------------------------
public class Board {
Panel boardPanel;
public Board (Panel boardPanel) {
this.boardPanel = boardPanel;
}
public void createButtons () {
// (create buttons with for statements - 2D array; add to boardPanel ..)
button.addActionListener(new Action());
}
// Action Listener (abstract class)
public class ActionListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
amountofButtonsPressed++;
if (amountofButtonsPressed >= amountOfButtons) {
// go back to the first class and continue
}
}
}
}
最佳答案
您的第一个类 - 主 UI - 应该实现操作监听器。
在第二个类中的某个初始化点,您必须注册主函数 类作为按钮的操作监听器。 你所有的组件都有一个名为 addActionListener() 的方法,使用这个方法 将第一个类作为参数传递。
public class Main implements ActionListener() {
public Main() {
new Class2(this);
}
public actionPerformed(Event e) {....}
}
public Class2 {
ActionListener a;
public Class2(ActionListener a) {
this.a = a;
...
...
button1.addActionListener(a);
button2.addActionListener(a);
}
}
关于Java:方法等待另一个类中的 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186265/