// JButtonClickedCounter.java package com.jdojo.swing.intro; import javax.swing.JFrame; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import javax.swing.JButton; import java.awt.event.ActionListener; public class JButtonClickedCounter extends JFrame { int counter; JButton counterButton = new JButton("Clicked #0"); JButton closeButton = new JButton("Close"); public JButtonClickedCounter() { super("JButton Clicked Counter"); this.initFrame(); } private void initFrame() { this.setDefaultCloseOperation(EXIT_ON_CLOSE); // Set a FlowLayout for the content pane this.setLayout(new FlowLayout()); // Add two JButtons to the content pane this.getContentPane().add(counterButton); this.getContentPane().add(closeButton); // Add an ActionListener to the counter JButton counterButton.addActionListener(e -> counterButton.setText("Clicked #" + ++counter)); // Add an ActionListener to the closeButton JButton closeButton.addActionListener(e -> System.exit(0)); } public static void main(String[] args) { JButtonClickedCounter frame = new JButtonClickedCounter(); frame.pack(); frame.setVisible(true); } }
Let’s look at one more example of adding an Action listener to JButton. This time, we add two buttons to a JFrame: a Close button and another to display the number of times it is clicked. Every time the second button is clicked, its text is updated to show the number of times it has been clicked. You need to use an instance variable to maintain the click count. Contains the complete code. Shows the JFrame when it is displayed and after the counter button has been clicked three times.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.