1/******************************************************************************
2 * Compilation: javac GUI.java
3 * Execution: java GUI
4 *
5 * A minimal Java program with a graphical user interface. The
6 * GUI prints out the number of times the user clicks a button.
7 *
8 * % java GUI
9 *
10 ******************************************************************************/
11
12import javax.swing.*;
13import java.awt.*;
14import java.awt.event.*;
15
16public class GUI implements ActionListener {
17 private int clicks = 0;
18 private JLabel label = new JLabel("Number of clicks: 0 ");
19 private JFrame frame = new JFrame();
20
21 public GUI() {
22
23 // the clickable button
24 JButton button = new JButton("Click Me");
25 button.addActionListener(this);
26
27 // the panel with the button and text
28 JPanel panel = new JPanel();
29 panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
30 panel.setLayout(new GridLayout(0, 1));
31 panel.add(button);
32 panel.add(label);
33
34 // set up the frame and display it
35 frame.add(panel, BorderLayout.CENTER);
36 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
37 frame.setTitle("GUI");
38 frame.pack();
39 frame.setVisible(true);
40 }
41
42 // process the button clicks
43 public void actionPerformed(ActionEvent e) {
44 clicks++;
45 label.setText("Number of clicks: " + clicks);
46 }
47
48 // create one Frame
49 public static void main(String[] args) {
50 new GUI();
51 }
52}
53
54