We use cookies to ensure you get the best experience on our website. Please review our Privacy Policy to learn more.
The JavaActionListener is an interface found in the java.awt.event
package; it is notified against the ActionEvent whenever the button or menu item is clicked. It has only one method: actionPerformed()
In the code below, when the user clicks the button, the program has an object that implements the ActionListner interface. The button is registered as an ActionListner using the addActionListner
method. As the button is clicked, the button fires an action event, and the ActionEvent object provides information about the event and its source.
Note: any action event can be associated with the button.
// importing required libraries. import java.awt.*; import java.awt.event.*; public class ActionListenerSample { public static void main(String[] arguments) { // frame set-up. Frame frm =new Frame("Java ActionListener Sample"); // ..........Textfield.............. // dimensions for textfield. final TextField textf=new TextField(); textf.setBounds(50,50, 150,20); // ..........Button.............. // dimensions for button. Button btn=new Button("Click Here"); btn.setBounds(50,100,60,30); // adding ActionListner on button btn.addActionListener(new ActionListener(){ // actionPerformed() function on the button pressing public void actionPerformed(ActionEvent evt){ textf.setText("Welcome to Javatpoint."); } }); // adding things in frame // button frm.add(btn); // text-bar frm.add(textf); // frame size, layout, visibility frm.setSize(400,400); frm.setLayout(null); frm.setVisible(true); } }