Working with Buttons in Java

Working with Buttons in Java

Every application has a lot of buttons. Some are dummy buttons while the others perform a certain action or call a certain event in the program. In this article, we will be creating buttons using Java Swing. JButtons are part of the javax package so if you want to add buttons to your code, you will have to import the following package:

import javax.swing.*;

The class declaration for creating a button is:
public class JButton extends AbstractButton implements Accessible

The button class can be initialized in several ways. Here is a list of constructors for this class:

  • JButton(): This creates a button without any text or icon.
  • JButton(String s): This will create a button with a String text stored in ‘s’.
  • JButton(Icon i): The Button will be created with the icon object.

Commonly used Methods of the JButton class

  • void setText(String s): This method is used to set a text that will appear as the button title.
  • String getText(): To return the text on the button.
  • void setEnabled(boolean b): To activate the button or deactivate it.
  • void setIcon(Icon b): To set an icon object to the button interface
  • Icon getIcon(): To get the icon assigned to the button.
  • void setMnemonic (int a): Used to set mnemonic on the button
  • void addActionListerner (ActionListener e): If you want the button to set off an event

Example

import java.awt.event.*;
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText(“This is a sample program");
}
}
);
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

OUPUT

An action has been associated with this button. So when you click on this button, the blank text field will show the following text “This is a sample program”.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.