我正在使用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) {
}
}
}
什么我在动作事件编写适用于所有的三个按钮,我怎样才能让这个每个按钮都有自己的功能? 非常感谢!
'我怎样才能让每个按钮都有自己的功能?' - 为每个按钮添加一个不同的ActionListener。 – camickr
您可以使用单个侦听器并使用'actionCommand'或'source'属性;你可以使用'clientProperty';你可以为每个按钮使用不同的监听器;你可以使用'Action' API ...许多有据可查的想法 – MadProgrammer