Button Click Event in Java

Sheeraz Gul May 31, 2022
Button Click Event in Java

We use an event listener to create a button click event in Java. This tutorial demonstrates how to create a button click event in Java.

Button Click Event in Java

Creating a button click event in Java is a step-by-step process.

  • Import all required packages, particularly the Java.awt.event.
  • Create a Main class from which the event will be called.
  • Create another class that will include the object of the JFrame class, user-defined methods, and constructor.
  • Next is to add the button to JFrame and create an object of the JButton class.
  • Next is to implement the actionListener interface.
  • Finally, we register the actionListener to the button.

Let’s try to implement an example that will change color on click in Java. See example:

package delftstack;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ActionEventDemo implements ActionListener {
    JFrame Demo_Frame=new JFrame();
    JButton Demo_Button=new JButton("Click Here");

    ActionEventDemo(){
    	Prepare_GUI();
    	Button_Properties();
    }

    public void Prepare_GUI(){
    	Demo_Frame.setTitle("Demo Window");
    	Demo_Frame.getContentPane().setLayout(null);
    	Demo_Frame.setVisible(true);
    	Demo_Frame.setBounds(400,100,400,400);
    	Demo_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void Button_Properties(){
        Demo_Button.setBounds(150,200,150,80);
        Demo_Frame.add(Demo_Button);
        Demo_Button.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //Changing Background Color
        Demo_Frame.getContentPane().setBackground(Color.red);

    }
}

public class On_Click {
    public static void main(String[] args)
    {
        new ActionEventDemo();
    }
}

The code above will create a frame with the button, which will change the color on click. See output:

Button Click Event

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook