How to work with buttons in Swing

The abstract class AbstractButton represents a button in Swing. The JButton is a subclass of AbstractButton that offers basic button functionality.

Constructors of the JButton class

The constructors of the JButton class are as follows. They can also be used to create a JButton object:

  1. The JButton() constructor is used to create a button with no text or icon.

  2. The JButton(text) constructor is used to create a button with the initial text, where text should be a string.

  3. The JButton(text, icon) constructor is used to create a button with the initial text and an icon, where text should be a string and icon is just an image.

Commonly used methods of JButton class

The most commonly used Methods of JButton class are as follows:

  1. addActionListener(ActionListener l): This method adds a listener to the specified JButton instance. The listener will be notified every time an action is performed via the button.

  2. void setText(text): This method sets the specified text on the button, where text should be an image.

  3. String getText(): This method is used to return the text of the button.

Code example

In the following example, we’ll design a graphical user interface in which a user enters text into a text box and then clicks a button, which converts the entire content to uppercase.

import javax.swing.*;
import java.awt.*;
import java.util.Locale;

class Main{

    public static void main(String[] args) {
        JFrame frame = new JFrame("JTextField Demo");
        JTextField jTextField = new JTextField();
        jTextField.setText("Type anything here");
        jTextField.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
        jTextField.setBounds(170, 90, 150, 40);
        JButton jButton = new JButton("Click Here");
        jButton.addActionListener(e -> jTextField.setText(jTextField.getText().toUpperCase(Locale.ROOT)));
        jButton.setBounds(30, 100, 50, 35);
        frame.add(jTextField);
        frame.add(jButton);
        frame.setSize(500,350);
        frame.setVisible(true);
    }
}
Code

Code explanation

  • Lines 1-3: Relevant classes and packages are imported.
  • Line 8: An instance of JFrame is created with the title name JTextField Demo.
  • Lines 9-12: An instance of JTextField is created that allows us to enter text.
  • Line 13: An instance of JButton is created with the Click Here text.
  • Line 14: An action listener is added to the button. Once the button is clicked, the action listener is invoked. In the action listener, the text entered in the text box is converted to uppercase.
  • Line 16: The text field created in line 9 is added to the frame.
  • Line 17: The button field created in line 13 is added to the frame.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved