We built our way up from the simplest GUI - a blank window -
to a GUI that responded to button-clicks: in particular, a GUI
with a button that incremented a visible counter with every
click. Below is a version with an addition I made while
talking to a student after class. It has a decrement as well
as an increment button. I give that here because it cleared
up a question for that student, so maybe it'll clear things up
for you.
import javax.swing.*;
import java.awt.event.*;
public class Ex1 extends JFrame
{
//-- Data Members -------------------------------//
private JLabel l;
private int c;
//-- Constructor --------------------------------//
public Ex1()
{
// Basic initialization
c = 0;
setSize(400,100);
setLocation(30,30);
setTitle("Java GUI Demo From Class");
addWindowListener(new CloseWindowListener());
// Create Panel
JPanel p = new JPanel();
add(p);
// Add text
l = new JLabel("count is " + c);
p.add(l);
// Add a button & create a listener and add it to the button
JButton b1 = new JButton("decrement");
p.add(b1);
b1.addActionListener(new ButtonDecActionListener());
// Add a button & create a listener and add it to the button
JButton b2 = new JButton("increment");
p.add(b2);
b2.addActionListener(new ButtonIncActionListener());
// Show the frame
setVisible(true);
}
//-- main function ------------------------------//
public static void main(String[] args) { JFrame f = new Ex1(); }
//-- listeners ----------------------------------//
class ButtonIncActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) { l.setText("count is " + ++c); }
}
class ButtonDecActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) { l.setText("count is " + --c); }
}
class CloseWindowListener implements WindowListener
{
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
}
}