Programming and Problem Solving with Java

(やまだぃちぅ) #1
8.3 Event Handling | 391

// Specify the size of the JFrame object
outputFrame.setSize(200, 75);
// Specify a layout manager for the content pane object
outputPane.setLayout(new FlowLayout());
// Add output to the content pane

// Make the JFrame object visible on the screen
outputFrame.setVisible(true);
}
}


We need to add our label and our button to the empty content pane. In past examples,
we’ve added a label with a statement such as the following, which instantiates an anonymous
label within the method call:


outputPane.add(new JLabel("" + number));


However, our problem calls for us to change the value of this label after it has been created.
We therefore need to store its address in a variable so that we can refer to the value after we
create it. The same is true for the button. Here’s how it should look instead, with the button
code added, too:


JLabel numberLabel;
JButton incrementButton;
number = 0;
numberLabel = new JLabel("" + number);
incrementButton = new JButton("Increment");
outputPane.add(numberLabel);
outputPane.add(incrementButton);


Our label and the variable numbershould be accessible to both mainand to the button
handler. We can take care of this task by writing them as class members. They do not have
to be accessible outside of the application class, so they can be private. And because we are
not creating instances of our application class, they should be declared as static.


private static intnumber;
private staticJLabel numberLabel;
private staticJButton incrementButton;


Here’s the button handler, which is just the skeleton we saw earlier, with our two lines
of executable statements inserted:


private static classButtonHandler implementsActionListener
{
public void actionPerformed(ActionEvent event) // Event handler method
{
number++;
numberLabel.setText("" + number);
}
} // End of ButtonHandler class

Free download pdf