[英]Multiple Java ActionListeners
So what I have been trying to do for past month is set multiple action listeners for my buttons without succes. 因此,过去一个月我一直在尝试为我的按钮设置多个动作监听器,但不会成功。 I have 3 buttons, and i want them to print some text on text area depending which button is pressed.
我有3个按钮,我希望他们根据按下的按钮在文本区域上打印一些文本。 So could somebody tell me where exactly do I have to write those listeners?
那么有人可以告诉我我该在哪里写那些听众? Thanks in advance.
提前致谢。
public class Lotto {
public static void main(String[] args) {
Color color1 = new Color(250,250,250);
Color color2 = new Color(200,200,200);
Color color3 = new Color(255,66,66);
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(400,400);
f1.setVisible(true);
f1.setLayout(null);
f1.setResizable(false);
JButton start = new JButton("Start");
start.setBounds(25,325,100,25);
f1.add(start);
JButton stop = new JButton("Stop");
stop.setBounds(150,325,100,25);
f1.add(stop);
JButton exit = new JButton("Exit");
exit.setBounds(275,325,100,25);
f1.add(exit);
JTextArea ta1 = new JTextArea("Your inputs");
ta1.setEditable(false);
ta1.setBounds(25,125,350,50);
ta1.setBackground(color2);
f1.add(ta1);
}
}
您可能想看一下Oracle的本教程。
Q: What have you tried? 问:您尝试了什么?
A: I didn't. 答:没有。
Anyway, AbstractButton.addActionListener
is what you're looking for. 无论如何,您正在寻找
AbstractButton.addActionListener
。 Either construct a separate ActionListener
for each JButton
instance, or construct a single ActionListener
that every JButton
instance will use. 任一构建一个单独
ActionListener
每个JButton
实例,或构建单个ActionListener
每个JButton
实例将使用。 With regard to the latter, use EventObject.getSource
to determine which component fired the event. 关于后者,请使用
EventObject.getSource
来确定触发该事件的组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.