Related Tags

What is the Java ActionListner?

java
actionlistner

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()

svg viewer

Example

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

Output of the above code

svg viewer
RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring