Java:方法在另一个类中等待 ActionListener [英] Java: Method wait for ActionListener in another class

查看:29
本文介绍了Java:方法在另一个类中等待 ActionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作棋盘游戏.一个类包含主 UI(保存、加载、标签等),另一个类包含实际的棋盘游戏按钮(8x8 按钮阵列).

I am making a board game. One class contains main UI (save, load, Labels etc.), and another class contains the actual board game buttons(8x8 array of buttons).

我希望第一个类等到第二个类中的所有按钮都被按下,然后继续执行程序.

I'd like the first class to wait until all the buttons in the second class are pressed and then continue with the program.

这是我应该用线程解决的问题吗?如果是这样,请有人向我发送正确的方向.

Is this something that I should fix with threading? If so can someone please send me in the right direction.

更新

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 - 应该实现动作监听器.

Your first class -main UI- should implement the action listener.

在第二节课的某个初始化点,你必须注册主类作为按钮的动作侦听器.你所有的组件都有一个叫做 addActionListener() 的方法,使用这个方法将第一个类作为参数传递.

At some initialization point in your second class you have to register the main class as the action listener for the buttons. All your components have a method called addActionListener(), use this method an pass the first class as parameter.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆