多个Java ActionListeners

时间:2011-12-10 15:59:57

标签: java swing jbutton actionlistener

所以我上个月试图做的就是为我的按钮设置多个动作监听器而没有成功。我有3个按钮,我希望他们在文本区域打印一些文本,具体取决于按下哪个按钮。那么有人可以告诉我,我究竟要在哪里写这些听众吗?提前谢谢。

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);
    }
}

2 个答案:

答案 0 :(得分:3)

您可能希望看一下Oracle的this教程。

答案 1 :(得分:3)

问:你有什么尝试? 答:我没有。


无论如何,AbstractButton.addActionListener正是你要找的。为每个ActionListener实例构建单独的JButton,或构造每个ActionListener实例将使用的单个JButton。关于后者,使用EventObject.getSource来确定触发事件的组件。

相关问题