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.
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.
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.
btnimg.jpg
JButtonOfImageEx.java
  1. import javax.swing.*;
  2. import java.awt.event.*;
  3. Public Class JButtonOfImageEx
  4. {
  5. JButtonOfImageEx()
  6. {
  7. JFrame frm = new JFrame();
  8. JButton btn = new JButton(new ImageIcon("btnimg.jpg"));
  9. btn.setBounds(145, 105, 105, 45);
  10. frm.add(btn);
  11. frm.setSize(630, 410);
  12. frm.setLayout(null);
  13. frm.setVisible(true);
  14. frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15. }
  16. public static void main(String[] args)
  17. {
  18. new JButtonOfImageEx();
  19. }
  20. }
Output
Fig-1.jpg
After pressing Enter in the command prompt we get the following (generates a new window that contains a button of image type).
Fig-2.jpg