how to define action listener for buttons in java

后端 未结 4 542
悲哀的现实
悲哀的现实 2021-01-26 08:31

I have a jframe that includes JButton.I have six buttons in this frame, but I don\'t know how to define action listener for this buttons.please help to solve this probl

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-26 08:38

    It's really simple.

    I suppose you have an instance of your button, right? Let's say that instance is called myButton.

    You can just add an action listener by calling addActionListener:

    myButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // Do whatever you like here
        }
    });
    

    Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.

提交回复
热议问题