DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Create Tables in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Leverage Lambdas for Cleaner Code
  • Build a Java Backend That Connects With Salesforce

Trending

  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Rust, WASM, and Edge: Next-Level Performance
  • Infrastructure as Code (IaC) Beyond the Basics
  • How to Convert XLS to XLSX in Java
  1. DZone
  2. Coding
  3. Java
  4. How to Create Buttons in Java Applications

How to Create Buttons in Java Applications

To use a button in an application or as part of a graphical user interface (GUI), developers need to create an instance of the JButton class.

By 
DZone Editorial user avatar
DZone Editorial
·
Nov. 14, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
5.2K Views

Join the DZone community and get the full member experience.

Join For Free

A button is a Swing component in Java that is usually used to register some action from a user. The action comes in the form of a button being clicked. To use a button in an application or as part of a graphical user interface (GUI), developers need to create an instance of the JButton class. JButton is a class that inherits from JComponent. Therefore, you can apply the JComponent features, such as layout and key bindings, on your buttons.


Enroll in Free Course: "Java Programming: Solving Problems in Software"

*Affiliate link. See Terms of Use.


In this tutorial, programmers will learn how to work with buttons in Java.

How to Use the JButton Class in Java

To create a button, simply instantiate the JButton class in your Java code like so:

Java
 
JButton button = new JButton("Button");


Programmers can supply a String (or icon) to the constructor of JButton as an identifier on the screen. Since JButton is a JComponent, you need to add it to a top level container, such as JFrame, JDialog, or JApplet in order for it to appear on screen.

The Java code example below uses the JFrame container:

Java
 
import javax.swing.*;
 
class SimpleButton{
 
   public static void main(String args[]){
 
       JFrame frame = new JFrame();
       JButton button = new JButton("Button");
 
       frame.add(button);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(400,400);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
    }
}


You should be able to see a button displayed on your screen when you run this code in your integrated development environment (IDE) or code editor:

A screenshot of the button displayed when you run the code in your IDE. 

It is important for developers to note that, when you run the code above, you may not get a similar display. This is because Swing components, by default, take on the look and feel of your application’s environment.

The example code shown does not achieve anything when you click or press the button. In practice, buttons are used to perform some action when a certain event on them occurs (i.e when pressed). This is referred to as listening for an event. The next section discusses how to listen for button events in Java. Learn: How to Create Tables in Java

How to Listen for Events on Buttons in Java

There are three steps programmers need to follow in order to listen for an event on a button. First, you need to implement the ActionListener interface on your event handling class. You could also extend a class that implements ActionListener instead. Here is how that looks in Java code:

Java
 
class EventClass implements ActionListener { 
//some code here
}


Second, you need to add an instance of the event handler as an action listener to one or more components using the addActionListener() method:

Java
 
GuiComponent.addActionListener(EventClassInstance);


The final step is to provide an implementation of the actionPerformed(ActionEvent e) method, which performs some action whenever an event is registered on a component. This method is the only method in the ActionListener interface and it is always called when an action is performed.

Read: Formatting Strings in Java: String.format() Method

Java Code Example for Button Click Events

The Java code example below displays the number of clicks a user has so far made when they click Button1:

Java
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class ClicksCount implements ActionListener{
 
   int count = 0;// store number of clicks
 
   ClicksCount(){
       JFrame frame = new JFrame();
       JButton button1 = new JButton("Button1");
       JButton button2 = new JButton("Button2");
       button1.addActionListener(this);
 
       frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
       frame.add(button1);
       frame.add(button2);
       frame.getRootPane().setDefaultButton(button1); // sets default button
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(450,450);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
 
   public void actionPerformed(ActionEvent e) {
       count++;
       System.out.println("You have clicked the ACTIVE button " + count + " times");
   }
      
   public static void main(String args[]){
 
       ClicksCount Clicks = new ClicksCount();
    }
}


When you compile and run the code above, you should see two buttons. If you take good notice, you will observe that Button1 has been highlighted. This is because it has been set as the default button:A screenshot showing that Button1 is highlighted after you compile and run the recent code example.


The default button is the button that initially appears to have the focus when the program is first run. When you press Enter on your keyboard, the program clicks this button since it was already selected by default. Pressing Tab will shift focus to the other button.

You can only have, at most, one default button, and you set it by calling the setDefaultButton() method on the root pane of a top-level container.

If you click Button2 in this example, you will notice that there is not a message displayed. This is because no event handler has been registered to listen for events on this button. In other words, you would have to use the addActionListener() method with Button2 to ensure that actionPerformed(ActionEvent e) is called when it is clicked.

Final Thoughts on Buttons and Events in Java

Since you are dealing with Swing components when using buttons and JButtons, remember to import the javax.swing library into your Java code. Also, in order to use an event listener, you need to add the java.awt library, as shown in the last code example. If you do not include these libraries, you will get a compilation error. Read more: Java Performance Tuning, Adjusting GC Threads for Optimal Results

Graphical user interface Integrated development environment Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Create Tables in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Leverage Lambdas for Cleaner Code
  • Build a Java Backend That Connects With Salesforce

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!