Introducing JButton Class of Swing in Java


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.


In this example; we create a button of an image type. We have used the following image to be displayed on the button.


import javax.swing.*;

import java.awt.event.*;

Public Class JButtonOfImageEx




        JFrame frm=new JFrame();  

        JButton btn=new JButton(new ImageIcon("btnimg.jpg"));

        btn.setBounds(145,105,105, 45);         







    public static void main(String[] args)


        new JButtonOfImageEx();





After pressing Enter in the command prompt we get the following (generates a new window that contains a button of image type).


Up Next
    Ebook Download
    View all
    View all