- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 add action listener to JButton in Java
The following is an example to add action listener to Button:
Example
package my; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingDemo { private JFrame frame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingDemo(){ prepareGUI(); } public static void main(String[] args){ SwingDemo swingControlDemo = new SwingDemo(); swingControlDemo.showButtonDemo(); } private void prepareGUI(){ frame = new JFrame("Java Swing"); frame.setSize(500,500); frame.setLayout(new GridLayout(3, 1)); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); frame.add(headerLabel); frame.add(controlPanel); frame.add(statusLabel); frame.setVisible(true); } private void showButtonDemo(){ headerLabel.setText("Button Demo"); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText("Ok Button is clicked here"); } }); controlPanel.add(okButton); frame.setVisible(true); } }
Output
Now, after clicking the OK button above, the following is visible:
- Related Articles
- How to set action command to JButton in Java
- How to add Icon to JButton in Java?
- How to implement an action listener using method reference in Java?
- How to add empty border to a JButton in Java?
- I want to call JButton doClick() method to simulate a click action in Java
- How can we add/insert a JButton to JTable cell in Java?
- How to Set OnClick Listener on Action Bar Title in Android?
- How to change JButton font dynamically in Java?
- How to add action icon in android?
- How to add action listeners to ContextMenu in JavaFX?
- How can we apply different borders to JButton in Java?
- How to implement a rollover effect for a JButton in Java?
- How can we set the margin to a JButton in Java?
- How to add an image to a button (action) in JavaFX?
- How can we set the shortcut key to a JButton in Java?

Advertisements