Java Reference
In-Depth Information
simple trick and define a final variable called self , which can be used in the anonymous inner class.
This is another pattern you might see occurring often when creating event listeners.
7.
It is always a good idea to separate logic code from interface code whenever you can. Therefore,
the actual calculation of a BMI is properly separated into its own method: calculateBMI . The
result is shown to the user with another message dialog.
serial version ids
When following along with the Try It Out, you might have spotted an Eclipse
warning saying that BMICalculator does not contain a serial version identifier.
Eclipse will offer to generate a random one for you, which boils down to a line of
code similar to this one being added to your class:
private static final long serialVersionUID = -8952857142790654268L;
Now what is this identifier and why is it useful? The reason behind this has to do
with serialization (storing objects in a format that allows you to read them back out
and initialize them as class instances again later). To make sure that the data of a
stored object still matches a class definition (as this might have changed over time),
Java also stores a special identifier that verifies that the object to be loaded back in
still matches the identifier of the class. As such, as the name suggests, the serial-
VersionUID is mainly helpful for versioning reasons (an object with UID 100 will
not be able to get instantiated to its class when the class definition is on version 101).
In most cases, Java can generate a serialVersionUID based on various aspects of
the class at hand. However, it is recommended that all serializable classes explicitly
declare serialVersionUID values, since the default serialVersionUID computa-
tion is sensitive to class details that may vary depending on compiler implementa-
tions. Since Swing components implement Serializable and because Eclipse cares
about best practices, it asks you to specify a serialVersionUID .
Since it is unlikely that you will start serializing Swing components (they shouldn't
contain important data anyway and should just concern themselves with UI), the best
thing to do if you want to avoid these warnings is to use the default UID everywhere:
private static final long serialVersionUID = 1L;
You can also turn off these warning by navigating to Window, Preferences,
Java Compiler Errors/Warnings and setting Serializable Class Without
serialVersionUID to Ignore under Potential Programming Problems.
Now take a closer look to see how event listeners work. Swing components hold a collection of lis-
tener objects, which have registered themselves to be interested in being notified whenever an event
occurs. For instance, for a JButton , you have seen how ActionListener objects can be registered
using the addActionListener method. Note that the same listener can in theory be registered with
multiple components.
 
Search WWH ::




Custom Search