Introducing JButton Class of Swing in Java

In this article we discuss the JButton class of Swing in Java.

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
  • JButton()
          Generates a button with no text or icon.
  • JButton(String str)
          Generates a specified text button.
  • JButton (Icon icn)
          Generates a specified icon object on a button.
 
Commonly used public methods
 
Some commonly used public methods of the Button class are:
  • void setText(String str)
          It sets a specified pattern or text on an image.
  • String getText()
          It returns the text of the button.
  • void setEnabled(boolean bln)
          It enables or disables the button.
  • void setIcon(Icon icn)
          It sets the specified icon on the button.
  • Icon getIcon()
          Gets the icon of the button.
  • void setMnemonic(int a)
          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.
 
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(14510510545);  
  10.   frm.add(btn);  
  11.   frm.setSize(630410);  
  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