This is the syntax highlighted version of GUI.java.
/*************************************************************************
* Compilation: javac GUI.java
* Execution: java GUI
*
* A minimal Java program with a graphical user interface. The
* GUI prints out the number of times the user clicks a button.
*
* % java GUI
*
*************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener {
private int clicks = 0;
private JLabel label = new JLabel("Number of clicks: 0 ");
public GUI() {
// the clickable button
JButton button = new JButton("Click Me");
button.addActionListener(this);
// layout
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(button);
panel.add(label);
getContentPane().add(panel, BorderLayout.CENTER);
// finish setting up the frame, and show it
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("GUI");
pack();
show();
}
// process the button clicks
public void actionPerformed(ActionEvent e) {
clicks++;
label.setText("Number of clicks: " + clicks);
};
// create one Frame
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Last updated: Wed Feb 11 18:05:27 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.