将多个actionListener添加到多个JButton中
问题描述:
我正在使用GUI并尝试获取不同的按钮来执行不同的任务。将多个actionListener添加到多个JButton中
当前,每个按钮导致相同的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);
}
}
我的ActionListener文件
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中写的任何东西都适用于所有的三个按钮,我怎样才能让每个按钮都有自己的功能?
您有类似的操作,您希望所有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语句在当前的监听器检查被点击的按钮,但我发现听众分开更容易保持较低的代码耦合。
答
我怎样才能让这个每个按钮都有自己的功能
添加不同的ActionListener到每个按钮。
更好的是,使用Action
而不是ActionListener。一个Action
只是一个奇特的ActionListener,它有几个属性。
有关定义内部类的示例,请参阅Swing教程How to Use Action中的部分,以便您可以为每个按钮创建唯一的Action
。
'我怎样才能让每个按钮都有自己的功能?' - 为每个按钮添加一个不同的ActionListener。 – camickr
您可以使用单个侦听器并使用'actionCommand'或'source'属性;你可以使用'clientProperty';你可以为每个按钮使用不同的监听器;你可以使用'Action' API ...许多有据可查的想法 – MadProgrammer