In this Java Swing tutorial, you will learn how to use button that allows the user to perform action in a desktop application.

You know, JButtonis a fundamental Swing component that renders a button on screen and responds to user’s clicking event for performing a specific task. This article summarizes common programming practices for using JButton in Swing.

Table of content:

    1. Creating a JButton object
    2. Adding the button to a container
    3. Adding event listener for JButton
    4. Setting mnemonic and hotkey for JButton
    5. Setting a JButton as the default button
    6. Customizing JButton’s apperance
    7. JButton demo program
 

1. Creating a JButton object



 

2. Adding the button to a container

frame.add(button, BorderLayout.CENTER);
panel.add(button, gridbagConstraints);
  

3. Adding event listener for JButton

public class App extends JFrame implements ActionListener {
	public App() {
		// creates the button...

		// adds event listener:
		button.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		// do something here...
	}
}
 

Here the container (JFrame) must implement the ActionListener interface and override the method actionPerformed().

 

4. Setting mnemonic and hotkey for JButton

String mapKey = "KEY_F2";
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke("F2"), mapKey);

button.getActionMap().put(mapKey, new AbstractAction() {
	public void actionPerformed(ActionEvent evt) {
		buttonActionPerformed(evt);
	}
});
 

5. Setting a JButton as the default button

A window can have a default button whose action will be invoked when the user hits Enter key. Here is the code to set the button as default button in the frame window:

getRootPane().setDefaultButton(button);
 

The default button is bold in the window like the 3rd button in this screenshot:

button set as default6. Customizing JButton’s appearance

button.setText("<html><color=blue><b>Edit</b></font></html>");
 

7. JButton demo program

For reference, we created a demo program which incorporates all the practices mentioned above. The program looks like this:

JButton demo program

You can download source code of this program in the attachment section.

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (SwingJButtonDemo.zip)SwingJButtonDemo.zip[ ]3 kB