The abstract class AbstractButton
represents a button in Swing. The JButton
is a subclass of AbstractButton
that offers basic button functionality.
JButton
classThe 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, where text
should be a string.
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.
JButton
classThe most commonly used Methods of JButton
class are as follows:
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.
void setText(text)
: This method sets the specified text on the button, where text
should be an image.
String getText()
: This method is used to return the text of the button.
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); } }
JFrame
is created with the title name JTextField Demo
.JTextField
is created that allows us to enter text.JButton
is created with the Click Here
text.Free Resources