Java JButton set button label on click

Description

Java JButton set button label on click

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {
  int counter;/*from  www  .ja  v  a 2s  . c  o  m*/

  public Main() {
    super("JButton Clicked Counter");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());
    JButton counterButton = new JButton("Clicked #0");

    getContentPane().add(counterButton);

    counterButton.addActionListener(e -> {
      counter++;
      counterButton.setText("Clicked #" + counter);
    });

  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related