Swing Button Event Handling - Java Swing

Java examples for Swing:JButton

Introduction

The following code adds an Action listener to the JButton.

Demo Code

import java.awt.FlowLayout;

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

public class Main extends JFrame {
  JButton closeButton = new JButton("Close");

  public Main() {
    super("Simplest Event Handling JFrame");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());

    getContentPane().add(closeButton);/*from   www . j a v a  2  s.co  m*/

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

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

Related Tutorials