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

    • Create a default button with a caption:
      JButton button = new JButton("Edit");

      Image: default button
    • Create a button with only an icon in the file system:
      JButton button = new JButton(new ImageIcon("images/start.gif"));
      Here the icon file start.gifis placed under images directory which is relative to the program.


      Image: icon onnly button

    • Create a button with only icon inside a jar file or in classpath:
      String iconPath = "/net/codejava/swing/jbutton/stop.jpg";
      Icon icon = new ImageIcon(getClass().getResource(iconPath));
      JButton button = new JButton(icon);
      Here the icon file stop.jpgis placed under a specific package in the classpath.


      Image: icon onnly button 2

    • Create a button with a caption and an icon:
      JButton button = new JButton("Start", new ImageIcon("images/start.gif"));

      Image: text and icon button
       



 

2. Adding the button to a container

  • A JButton is usually added to a JPanel, a JFrame, a JDialog or a JApplet:
    frame.add(button);
    dialog.add(button);
    panel.add(button);
    applet.getContentPane().add(button);
     

  • Adding a JButton to a container with a specific layout manager:
frame.add(button, BorderLayout.CENTER);
panel.add(button, gridbagConstraints);
  

3. Adding event listener for JButton

  • Adding an event listener using anonymous class (shortcut way):
    button.addActionListener(new ActionListener() {
    	@Override
    	public void actionPerformed(ActionEvent evt) {
    		// do everything here...
    	}
    });
     

  • Adding an event listener using anonymous class and an event handler method (recommended):
    button.addActionListener(new ActionListener() {
    	@Override
    	public void actionPerformed(ActionEvent evt) {
    		// delegate to event handler method
    		buttonActionPerformed(evt);
    	}
    });
     

    The event handler method is declared as follows:

    private void buttonActionPerformed(ActionEvent evt) {
    	// do something here...
    }
     

  • Let the container listens to JButton’s click event (not recommended):
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

  • Set mnemonic key Alt + Efor the button whose caption is “Edit”:
    button.setMnemonic(KeyEvent.VK_E);

    The letter E is underlined: mnemonic buttonso user can invoke that button’s action by pressing Alt + Einstead of clicking mouse.  

  • Set F2 as the hot key to invoke the button’s action:
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

  • Change font style, background color and foreground color of the button:
    button.setFont(new java.awt.Font("Arial", Font.BOLD, 14));
    button.setBackground(Color.YELLOW);
    button.setForeground(Color.BLUE);

    Image: colorful button 

  • Change font style using HTML code:
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

Add comment

   


Comments 

#2test2021-01-18 04:16
merci
I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton("Format Citation: "
+ strTemplateName
Quote
#1Roger2020-06-24 07:52
I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton("Format Citation: "
+ strTemplateName
+ " - "
+ strTemplateCode),
BorderLayout.NORTH);
Quote