8.3 Event Handling | 393
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Specify the frame size
outputFrame.setSize(200, 75);
// Specify a layout manager
outputPane.setLayout(new FlowLayout());
// Prepare label and button for user interface
number = 0;
numberLabel = new JLabel("" + number);
incrementButton = new JButton("Increment");
incrementListener = new ButtonHandler();
incrementButton.addActionListener(incrementListener);
// Add output to the content pane
outputPane.add(numberLabel);
outputPane.add(incrementButton);
// Make the JFrame visible
outputFrame.setVisible(true);
}
}
Here’s what the application displays after the button has been clicked repeatedly.
Event Loops
OurSimpleButtonexample allows us to click the button as many times as we wish. Each
time the button is clicked, the number is incremented. When we finally grow tired of
watching the number increase, we simply close the window to stop the appli-
cation. Without explicitly intending to do so, we’ve implemented another con-
trol structure: anevent loop. Recall our discussion of looping from Chapter 5,
where we explicitly used awhileloop. Here the loop is implicit—no Java state-
ment spells it out. Figure 8.5 illustrates this loop.
In Chapter 5, we saw that loops can be broken down into six parts: initial-
ization, entry, repeated process, exit condition, exit condition update, and exit.
Event loops have a similar breakdown. We initialized our loop by setting up the
button and its event handler, and by setting numberto zero and creating the label. We enter
the loop when the frame is displayed on the screen. The repeated process is to increment num-
berand redisplay it. Our exit condition is the closing of the window, which is handled inde-
pendently by another event handler that is built into objects of the class JFrame. Thus we don’t
have to explicitly program the exit condition update. Later in the chapter, when we look at
Event loop Repeating an ac-
tion in response to repeated
events