- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set action command to JButton in Java
With set action command, here we are displaying a message in the console on the click of a button.
Set the button first:
JButton btn = new JButton("Demo Button");
Now, set Action Listener to fire when the button is clicked:
ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent event) { String str = event.getActionCommand(); System.out.println("Clicked = " + str); } };
The following is an example to set action command to JButton:
Example
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; public class SwingDemo { public static void main(final String args[]) { JButton btn = new JButton("Demo Button"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent event) { String str = event.getActionCommand(); System.out.println("Clicked = " + str); } }; btn.setActionCommand("FirstButton"); btn.addActionListener(actionListener); JOptionPane.showMessageDialog(null, btn); } }
Output
When you will click the “Demo Button” above, the following text would be visible in EclipseIDE output window:
- Related Articles
- How to add action listener to JButton in Java
- How can we set the margin to a JButton in Java?
- I want to call JButton doClick() method to simulate a click action in Java
- How can we set the shortcut key to a JButton in Java?
- How to add Icon to JButton in Java?
- How to change JButton font dynamically in Java?
- How to add empty border to a JButton in Java?
- How can we apply different borders to JButton in Java?
- How to set action to a RadioButton in JavaFX?
- How to implement a rollover effect for a JButton in Java?
- How to set subtitle for action bar in android?
- How to set title for action bar in android?
- How can we add/insert a JButton to JTable cell in Java?
- How to set action to a slider using JavaFX?
- How to use the Set-Location command in PowerShell?

Advertisements