A JFrame With Two Buttons With Actions - Java Swing

Java examples for Swing:JButton

Description

A JFrame With Two Buttons With Actions

Demo Code

import java.awt.FlowLayout;

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

public class Main extends JFrame {
  int counter;/*from w w  w .ja va 2  s .co  m*/
  JButton counterButton = new JButton("Clicked #0");
  JButton closeButton = new JButton("Close");

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

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());

    getContentPane().add(counterButton);
    getContentPane().add(closeButton);

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

    closeButton.addActionListener(e -> {
      System.exit(0);
    });
  }

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

Related Tutorials