Java Reference
In-Depth Information
figure 11-20
How It Works
This is how it works:
1.
Instead of putting all the code in a single
main
method, like in the trivial examples before, now a
proper class, extending
JFrame
, is created.
2.
Note also the addition of the following pattern in the
main
method:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Execute UI code here
}
});
Using the static
invokeLater
method of the
SwingUtilities
class ensures that all UI‐related code is executed on
the Event Dispatch Thread. You'll see later on what this means exactly. For now, just keep this pattern in mind.
3.
A set of methods is defined to create “pretty” text fields, buttons, and labels. Your definition of
pretty might vary, so feel free to change and experiment with these methods.
4.
Then the GUI is set up within the constructor of the class. A
BoxLayout
is used here, and all the
components are stacked under each other.
5.
The important code is located in the
addActionListener
method. As the name suggests,
this method allows you to add a listener to your
btnCalc
button that's notified whenever an
ActionEvent
occurs. The listener itself is constructed by using an anonymous inner class (
new
ActionListener(){...}
), a pattern that you will see occurring often for event listeners. This
anonymous class needs to override and specify one method,
actionPerformed
, which will be
called by the button whenever the user performs an action. In the case of a
JButton
, this means
whenever the button is activated (clicked, focused on, and then Enter is pressed).
6.
Inside the action listener, the mass and height are taken from the text fields, and a check is done to
see if these fields contain invalid input (if they do, an error is displayed). To show messages, another
Swing component called
JOptionPane
shows the message dialogs using a single static method. The
first argument indicates the parent component of the message dialog to be shown, which in this case
means the BMI Calculator. You cannot, however, just pass
this
, as
this
, in this context, would
resolve to the anonymous
ActionListener
object, not to the
BMICalculator
object. Instead, use a
Search WWH ::
Custom Search