- JButton basic tutorial and examples
- 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 appearance
- 7. JButton demo program
- Other Java Swing Tutorials:
- About the Author:
- Add comment
- Comments
- Java JButton Tutorial with ActionListener Programming Examples
- Constructors
- Methods
- Programming Example
- Action Listener
- Summary
JButton basic tutorial and examples
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, JButton is 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
JButton button = new JButton("Edit");
Image:
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.gif is placed under images directory which is relative to the program.
Image:
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.jpg is placed under a specific package in the classpath.
Image:
Create a button with a caption and an icon:
JButton button = new JButton("Start", new ImageIcon("images/start.gif"));
Image:
2. Adding the button to a container
frame.add(button); dialog.add(button); panel.add(button); applet.getContentPane().add(button);
frame.add(button, BorderLayout.CENTER); panel.add(button, gridbagConstraints);
3. Adding event listener for JButton
button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // do everything here. >>);
button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // delegate to event handler method buttonActionPerformed(evt); >>);
private void buttonActionPerformed(ActionEvent evt) < // do something here. >
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
button.setMnemonic(KeyEvent.VK_E);
The letter E is underlined: so user can invoke that button’s action by pressing Alt + Einstead of clicking mouse.
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 3 rd button in this screenshot:
6. Customizing JButton’s appearance
button.setFont(new java.awt.Font("Arial", Font.BOLD, 14)); button.setBackground(Color.YELLOW); button.setForeground(Color.BLUE);
Image:
7. JButton demo program
For reference, we created a demo program which incorporates all the practices mentioned above. The program looks like this:
You can download source code of this program in the attachment section.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh 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.
Add comment
Comments
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
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);
CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.
Copyright © 2012 — 2023 CodeJava.net, all rights reserved.
Java JButton Tutorial with ActionListener Programming Examples
Java JButton in swing is used for performing action when clicked on it. This action might be getting data from input field, saving or retrieving data to database or performing and displaying calculation result in swing frame. Following classes and methods are used for implementing JButton in Swing.
Constructors
Constructor | Description |
---|---|
JButton() | It creates a button with no text and icon. |
JButton(String s) | It creates a button with the specified text. |
JButton(Icon i) | It creates a button with the specified icon object. |
Methods
Methods | Description |
---|---|
void setText(String s) | It is used to set specified text on button |
String getText() | It is used to return the text of the button. |
void setEnabled(boolean b) | It is used to enable or disable the button. |
void setIcon(Icon b) | It is used to set the specified Icon on the button. |
Icon getIcon() | It is used to get the Icon of the button. |
void setMnemonic(int a) | It is used to set the mnemonic on the button. |
void addActionListener (ActionListener a) | It is used to add the action listener to this object. |
Programming Example
package Test.MainJava.com; import javax.swing.*; public class JButton_Example < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible >>
Output:
Action Listener
This was the simple JButton example that performed nothing when clicking on it. Now, I will add action listener so, this button will perform some action on clicking.
package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public FirstAppxample < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height b.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < JOptionPane.showMessageDialog(null, "Hello World"); >>); frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible > >
Output
package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButton_Example < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height b.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < showmessage(); >>); b.addActionListener(null); frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible > public static void showmessage() < JOptionPane.showMessageDialog(null, "Hello World"); >>
Output
package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButton_Example < protected JButton b1, b2; protected JFrame frame; public void TrackButton() < b1=new JButton("Button1"); b1.setBounds(140,100,120,40); b1.addActionListener(actions); b2=new JButton("Button2"); b2.setBounds(140,150,120,40); b2.addActionListener(actions); frame=new JFrame(); frame.add(b1); frame.add(b2); frame.setSize(400, 500); frame.setLayout(null); frame.setVisible(true); >private ActionListener actions = new ActionListener() < @Override public void actionPerformed(ActionEvent e) < if(e.getSource() == b1) < msg1(); >else if(e.getSource() == b2) < msg2(); >> >; public void msg1() < JOptionPane.showMessageDialog(null, "I am Button 1"); >public void msg2() < JOptionPane.showMessageDialog(null, "I am Button 2"); >public static void main(String[] args) < JButton_Example jb=new JButton_Example(); jb.TrackButton(); >>
Output
Summary
In this tutorial you learn how to play with JButton in Swing Application. I have tried to explain JButton with suitable, easy and complete programming example. In the next chapter you will learn some inputs field of Swing like JTextField, JPasswordField, JTextArea and JLabel