【发布时间】: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。 -
您可以使用单个侦听器并使用
actionCommand或source属性;你可以使用clientProperty;您可以为每个按钮使用单独的侦听器;你可以使用ActionAPI ...很多有据可查的想法
标签: java swing actionlistener