JButton Images Example

JButton Images Example


JButton Images Example Note: It is advised to read Java JFC Swing Introduction and Swing Overview before reading this.

A button is a component the user clicks to trigger a specific action and is very often used in GUI programming. A Java program can use several types of buttons, including command buttons, check boxes, toggle buttons and radio buttons etc. Following is the hierarchy of JButton. JButton is the corresponds to Button of AWT.

JButton Images Example

JButton Hierarccy

Command buttons are created with class JButton, which inherits from class AbstractButton. The text on the face of a JButton is called button label. A GUI can have many JButtons, but each button label should typically be unique(to avoid confusion to the user). Button changes its appearance while clicking indicating a push(click) is performed. Buttons generate action event. We must register the button with ActionListener interface.

The following code on JButton Images Example illustrates the creation of different types of buttons.


JButton Images Example
Output Screenshot on JButton Images Example

Container c = getContentPane();
c.setLayout(new GridLayout(4,1));

As JFrame is a heavyweight container, all the GUI components must be added to Container. Read more about light and heavyweight containers in Java JFC Swing Introduction and Swing Overview.

JButton btn1 = new JButton(“Sparrow Bird”);
c.add(btn1);

In the above JButton btn1, only label is added as you did in AWT Button. Observe, the JButton is added to container and not directly to JFrame.

ImageIcon ic2 = new ImageIcon(“bird1.gif”);
JButton btn2 = new JButton(ic2);

Jbutton btn2 is added with only image and not with a label. Any image object of any format (like .gif, .jpg) should be converted into an object of javax.swing.ImageIcon before added to swing component.

ImageIcon ic3 = new ImageIcon(“bird2.gif”);
JButton btn3 = new JButton(“Sparrow Bird”,ic3);

For the JButton btn3, both label and image are added. By default, label is added to the right of image. That is, first image and then its besides right-side, label comes. See the output screen above. This default nature is overcome in the followin JButton btn4.

ImageIcon ic4 = new ImageIcon(“bird3.gif”);
JButton btn4 = new JButton(“Sparrow Bird”,ic4);
btn4.setHorizontalTextPosition(SwingConstants.LEFT);

For JButton btn4, label is added to the left of image using SwingConstants.LEFT.

2 thoughts on “JButton Images Example

Leave a Reply

Your email address will not be published. Required fields are marked *