首页 > 解决方案 > 如何从三个选项中比较两个按钮按下?

问题描述

我有 3 个按钮

b1 b2 b3

我现在想轮流按下这些按钮。因此,我按下第一个,另一个人按下第二个。所以在第二回合之后,我会比较按钮的名称。

b1.addActionListener(new ActionListener() {
    public void actionPerformed( ActionEvent event ) {
        b1.setEnabled(false);
        if (!b1.isEnabled() && !b2.isEnabled()) {
            //computeWinner(b1.getText(), b2.getText());
        } else if(!b1.isEnabled() && !b3.isEnabled()) {
            //computeWinner(b1.getText(), b2.getText());
        }
    }
});

这是我认为可行的,但是这有很多问题,首先,因为我禁用了按钮,所以第二个用户总是少一个选项。其次,if 语句似乎不起作用?我应该如何比较 JButton b3 = new JButton ("hello"); <- 你好按钮的标签?

编辑:我能够成功比较这两个按钮。现在我唯一的问题是,对于第二个玩家,其中一个按钮被禁用(如何在不禁用它们的情况下捕获第一个按钮按下和第二个按钮?)。而且经过比较后,我不知道如何重新设置板子。(对于一定数量的循环。)

感谢您的帮助!

标签: javaswinguser-interface

解决方案


The following code will print the label of the button which has been pressed. I hope, you should be able to proceed from here. Feel free to let me know if you face any further issue.

ActionListener actionListener = new ActionListener(){
  public void actionPerformed(ActionEvent actionEvent) {
      System.out.println(actionEvent.getActionCommand());
  }
};

推荐阅读