Completing a Standard Window
Here are some coding standards to consider for every program that uses a JFrame.
Serial version UID
Some development environments display a warning for any class that extends a windows component, stating that “The serializable class does not declare a static final serialVersionUID
of type long
”.
- Add a
private static final long
instance variable calledserialVersionUID
with a value of1L
.
...
public class WizardOfYesNo extends JFrame {
private static final long serialVersionUID = 1L;
private static final String[] ANSWER = {"Yes",
...
Running the program should produce the same results as before.
Event queue
Did you notice the import statement that Eclipse
inserted for JFrame
? The import statement shows JFrame
is in the javax.swing
package. Therefore, JFrame
is a Swing
component. Java
expects all Swing
objects to be created on an event queue.
Create WizardOfYesNo
on the EventQueue
- Replace the code in the
main()
method with code exactly as shown.
...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { public void run() {
new WizardOfYesNo();
}
});
}
...
The program should still run with the same results, but may now run faster.
Cross-platform look and feel
Windows, dialogs, and the components they contain, look different on computers with different operating systems. This difference affects how code should be written. In order to get program code in this course to work the same, regardless what operating system you are running on, use the Cross-Platform look and feel.
Use the cross-clatform look and feel
- Add a
try/catch
block to the beginning ofmain()
. - In the
try
block, create a new string calledclassName
, initialized by getting the cross-platform look and feel fromUIManager
. (Hint: useUIManager
'sgetCrossPlatformLookAndFeelClassName()
method.) - Set the look and feel with
className
. (Hint: useUIManager
'ssetLookAndFeel()
method.) - In the catch block, catch any Exception and do nothing when the exception is caught. (Hint:
catch Exception. Hint: do nothing by using empty brackets,
{}
).
...
public static void main(String[] args) {
try {
String className =
UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
}
catch (Exception e){}
EventQueue.invokeLater(new Runnable() {
public void run() {
new WizardOfYesNo();
...
The window should now have the standard Java metallic look and feel.
Get hands-on with 1200+ tech skills courses.