Introducing 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

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

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

Up Next
    Ebook Download
    View all
    Learn
    View all