Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created May 14, 2019 20:51
Show Gist options
  • Save luisenriquecorona/a6cd7e606da509d6e7bb41ec20fc0f1c to your computer and use it in GitHub Desktop.
Save luisenriquecorona/a6cd7e606da509d6e7bb41ec20fc0f1c to your computer and use it in GitHub Desktop.
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 …
// 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment