Introduction
In this article we discuss the JButton class of Swing in Java.
What JButton class is
This class creates a button that has a platform-independent implementation. The JButton class always extends the AbstractButton class.
Commonly used Constructors
Generates a button with no text or icon.
Generates a specified text button.
Generates a specified icon object on a button.
Commonly used public methods
Some commonly used public methods of the Button class are:
It sets a specified pattern or text on an image.
It returns the text of the button.
- void setEnabled(boolean bln)
It enables or disables the button.
It sets the specified icon on the button.
Gets the icon of the button.
Sets the mnemonic on the button.
- void addActionListener(ActionListener al)
Adds the action listener to this object.
Example
In this example; we create a button of an image type. We have used the following image to be displayed on the button.
JButtonOfImageEx.java
import javax.swing.*;
import java.awt.event.*;
Public Class JButtonOfImageEx
{
JButtonOfImageEx()
{
JFrame frm=new JFrame();
JButton btn=new JButton(new ImageIcon("btnimg.jpg"));
btn.setBounds(145,105,105, 45);
frm.add(btn);
frm.setSize(630,410);
frm.setLayout(null);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JButtonOfImageEx();
}
}
Output
After pressing Enter in the command prompt we get the following (generates a new window that contains a button of image type).