JButton with ActionListener and ActionEvent

Event Handling

When the user clicks a button or perform any other interface related action in your application, an interface event occurs. Each components has a predefined set of events. When an event occurs in your application, the application notified and takes the appropriate action.

Events are passed from source controls to Listener objects. That means you will connect a Listener to a button. So, when an event occurs object will “hear” it. This is accomplished by addActionListener() method.

JButton.addActionListener(this);

The This keyword is refers the object you have currently in. Catch the events sent to you by overriding the actionPerformed() method and adding your own version.

public void actionPerformed(ActionEvent eve) {

}

The actionEvent object holds information about the event that occurred.

Program

rtert

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Frame extends JFrame implements ActionListener{
    
    private JButton jb;
    
    Frame()
    {
        setTitle("JButton with ActionListener");
        setLayout(new FlowLayout());
        setButton();
        setAction();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setButton()
    {
        jb = new JButton("JButton");
        add(jb);
    }
    
    private void setAction()
    {
        jb.addActionListener(this);
    }
    
    public void actionPerformed(ActionEvent eve)
    {
        JOptionPane.showMessageDialog(rootPane, "JButton Pressed");
    }
}

public class Javaapp {
   
    public static void main(String[] args) {
        
        Frame frame = new Frame();
    }
}

Leave a Comment