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:
-
The
JButton()constructor is used to create a button with no text or icon. -
The
JButton(text)constructor is used to create a button with the initial text, wheretextshould be a string. -
The
JButton(text, icon)constructor is used to create a button with the initial text and an icon, wheretextshould be a string andiconis just an image.
Commonly used methods of JButton class
The most commonly used Methods of JButton class are as follows:
-
addActionListener(ActionListener l): This method adds a listener to the specifiedJButtoninstance. The listener will be notified every time an action is performed via the button. -
void setText(text): This method sets the specified text on the button, wheretextshould be an image. -
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 explanation
- Lines 1-3: Relevant classes and packages are imported.
- Line 8: An instance of
JFrameis created with the title nameJTextField Demo. - Lines 9-12: An instance of
JTextFieldis created that allows us to enter text. - Line 13: An instance of
JButtonis created with theClick Heretext. - 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