Saturday, August 24, 2013


JButton component represents a pushing button in SWING package. On the button created by the JButton class, you can place an image and text. This button can generate an action event. There are two ways to receive the action event of the button. One way is using the ActionListener interface. The alternative is using the Action interface. By using AbstractAction class that implements the Action interface, you can only receive the event but also can specify the properties (icon and text) of the button. See the example code below.  

Constructors of the JButton class:
creates a new button without image or text.
-JButton(String text)
creates a new button with text to describe it.
-JButton(Action action)
creates a new button with its properties (icon and text) taken from the Action interface implementation.
-JButton(Icon icon)
creates a new button with an icon image.
-JButton(String text,Icon icon)
creates a new button with text and an icon image.

Useful methods of the JButton class:
gets the text of the button.
-setAction(Action action):void
sets the Action implementation to the button.
-setMnemonic(int key):void
sets the mnemonic key to the button. This key when combined with the mouseless modifier key (usually Alt) will activate the button when it is focused.

-setText(String text):void
sets text of the button.

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

class JButtonShow extends JFrame{
JButtonShow(String title){
setLayout(new FlowLayout(FlowLayout.LEFT));
Container contpane=getContentPane();
Image imgnew=Toolkit.getDefaultToolkit().getImage("newicon.png");
JButton btnew=new JButton();
btnew.setAction(new AAction("New",new ImageIcon(imgnew)));
Image imgopen=Toolkit.getDefaultToolkit().getImage("openicon.png");
JButton btopen=new JButton();
btopen.setAction(new AAction("Open",new ImageIcon(imgopen)));


class AAction extends AbstractAction{

AAction(String text, ImageIcon icon){

public void actionPerformed(ActionEvent e){

public class JFrameSwing {
public static void main(String[] args){
new JButtonShow("JButton");

JButton Swing

The getActionCommand() method of the ActionEvent class returns the text that is shown on the button. If you have many buttons on the window, to determine which button is pushed, you need to compare this text with text of the button. For example, to check whether the New button is pushed, you can write the code shown below:
//do something

1 comment:

  1. nice article in your blog.thank you for sharing useful info.
    web programming tutorial