JButton Border Example

JButton Border Example

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

In the following program on JButton Border Example, special features like mnemonic(shortcut key), setting borders and images are discussed.

JButton Border Example

ImageIcon ic1 = new ImageIcon(“bird1.gif”);

Output screenshot on JButton Border Example

ImageIcon is a class from Javax.swing package which creates an image of icon size to be used along with components. Any image of any format (like .gif,.jpg, .png) etc. is to be converted into an object of ImageIcon before added to any swing component.

rb = new JButton(“Red”, ic1);

The above statement creates a button object rb with label "Red" and keeps an icon(ic1 that represents bird1.gif) on the button .


setRolloverIcon(ic2) is an attractive feature for a button. When the mouse cursor is taken on to the button, the default icon on the button ic1(of bird1) is changed to ic2(of tomcat). When the cursor is again moved away from the button, the default icon bird1 is displayed. That is, the image on the button is toggled between ic1 and ic2.


setMnemonic(char ch) method sets a keyboard shortcut to the button. That is, an event can be generated either by the usual way of clicking a mouse on the button or by pressing alt + ch.

Another property we can set to the button(which we have not set in this program) is tool tip which can be set as follows:

rb.setToolTipText(“click changes to red”);

String str = e.getActionCommand( );

getActionCommand() method of ActionEvent returns the label of the button clicked(in case of text field, it is the text entered).

JButton btn = (JButton) e.getSource();

getSource() method of the ActionEvent class returns the object of the button in an object form of Object class which must be type casted to JButton. This, we have done earlier in case of JTextField.

JFrame is closed using anonymous inner class of WindowAdapter.

bb.setBorder(BorderFactory.createTitledBorder(“Blue Button”));

One of the strengths of Swing is giving choicest border around a component. In the above statement, around the JButton bb, a border with a title "Blue Button" is given.

Other borders that can be applied are:

BorderFactory: createTitledBorder, createEtchedBorder, createBevelBorder, createRaisedBevelBorder, createLoweredBevelBorder, createLineBorder, createMatteBorder, createCompoundBorder, and createEmptyBorder

2 thoughts on “JButton Border Example

Leave a Reply

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