Swing JButton

The JButton class provides the functionality of a push button. It allows an icon, a string, or both to be associated with the push button.

JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)

Here, str and icon are the strings and icons used for the button.

When the button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed() method of the registered ActionListener, you can obtain the action command string associated with the button. By default, this is the string displayed inside the button. However, you can set the action command by calling setActionCommand() on the button. You can obtain the action command by calling getActionCommand() on the event object. It is declared like this:

String getActionCommand()

The action command identifies the button. Thus, when using two or more buttons within the same application, the action command gives you an easy way to determine which button was pressed.

Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Button extends JApplet implements ActionListener
{
JLabel jlab;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("India.gif");
JButton jb = new JButton(India);
jb.setActionCommand("India");
jb.addActionListener(this);
add(jb);
ImageIcon germany = new ImageIcon("America.gif");
jb = new JButton(America);
jb.setActionCommand("America");
jb.addActionListener(this);
add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
add(jb);
jlab = new JLabel("Choose a Flag");
add(jlab);
}
public void actionPerformed(ActionEvent ae)
{
jlab.setText("You are selected " + ae.getActionCommand());
}
}