【问题标题】:Add multiple actionListener to multiple JButtons将多个 actionListener 添加到多个 JButtons
【发布时间】:2017-10-13 04:03:06
【问题描述】:

我正在开发一个 GUI,并尝试使用不同的按钮来执行不同的任务。

目前,每个按钮都指向同一个 ActionListener。

public class GUIController {

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
public static void createAndShowGUI() {
    JFrame frame = new JFrame("GUI");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridLayout(3,3));

    JLabel leight =new JLabel("8");
    frame.getContentPane().add(leight);
    JLabel lfive =new JLabel("0");
    frame.getContentPane().add(lfive);
    JLabel lthree =new JLabel("0");
    frame.getContentPane().add(lthree);

    JButton beight =new JButton("Jug 8");
    frame.getContentPane().add(beight);
    JButton bfive =new JButton("Jug 5");
    frame.getContentPane().add(bfive);
    JButton bthree =new JButton("Jug 3");
    frame.getContentPane().add(bthree);

    LISTN ccal = new LISTN (leight,lfive,lthree);

    beight.addActionListener(ccal);
    bfive.addActionListener(ccal);
    bthree.addActionListener(ccal);

    frame.pack();
    frame.setVisible(true);

}

}

我的动作监听器文件

public class JugPuzzleGUILISTN implements ActionListener {
JLabel leight;
JLabel lfive;
JLabel lthree;

JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){
    this.leight = leight;
    this.lfive = lfive;
    this.lthree = lthree;
}

public void actionPerformed(ActionEvent e) {
    }

}
}

我在 ActionEvent 中写的任何东西都适用于所有三个按钮,我怎样才能让每个按钮都有自己的功能? 非常感谢!

【问题讨论】:

  • how can I make it so that each button has their own function? - 为每个按钮添加不同的 ActionListener。
  • 您可以使用单个侦听器并使用actionCommandsource 属性;你可以使用clientProperty;您可以为每个按钮使用单独的侦听器;你可以使用Action API ...很多有据可查的想法

标签: java swing actionlistener


【解决方案1】:

我怎样才能让每个按钮都有自己的功能

为每个按钮添加不同的 ActionListener。

更好的是,使用 Action 而不是 ActionListener。 Action 只是一个花哨的 ActionListener,它有更多的属性。

阅读 How to Use Action 上的 Swing 教程部分,了解定义内部类的示例,以便您可以为每个按钮创建唯一的 Action

【讨论】:

    【解决方案2】:

    我在 ActionEvent 中写的任何东西都适用于所有三个按钮,我怎样才能让每个按钮都有自己的功能?

    您有类似的操作,您希望所有 3 个按钮都能触发。但是,您还可以为每个按钮实现不同的功能。

    其中一种方法将创建另外 3 个侦听器,每个侦听器都将添加到各自的按钮中。所以现在每个按钮都将添加 2 个侦听器(您当前的侦听器 + 新创建的侦听器)。

    //Example:
    
    beight.addActionListener(ccal);
    bfive.addActionListener(ccal);
    bthree.addActionListener(ccal);
    
    beight.addActionListener(ccal_beight);
    bfive.addActionListener(ccal_bfive);
    bthree.addActionListener(ccal_bthree);
    

    还有其他方法,例如在当前侦听器中使用 if 语句来检查单击了哪个按钮,但我发现单独的侦听器更易于维护,代码耦合度较低。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 2015-11-07
      • 2011-07-06
      • 1970-01-01
      • 2015-07-18
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多