Java Swing
Java Swing
Common order:
1. get screen looking right, no functionality
2. add functionality
Another possibility:
1. put components on screen, quick & sloppy
2. add functionality, debug
3. improve appearance
CISC 323 winter 2006, Swing 8
Kinds of Components
Task for Assignment 3: design user interface
What kinds of components can you use?
• buttons
• text fields
• labels
• pop-up windows (JOptionPane & dialogs)
• combo boxes (drop-down list of choices)
• optional: different fonts & colours, icons
"baby" demos
Purpose: show how to get a simple frame onto the screen
Summary:
• convention is to subclass JFrame
• must explicitly make the frame visible
• must set size or get tiny frame
• must specify window-closing behavior
Programmer's job:
give layout manager some general instructions
Rules:
• components always at preferred sizes, never stretched
• breaks into multiple rows if necessary
• can specify alignment
on web: SimplePanelDemo.java
Methods:
void setText(String text);
String getText();
void setEnabled(boolean);
Methods:
void setText(String text);
String getText();
to create:
JTextField nameField = new JTextField(10);
or:
JTextField nameField = new JTextField("Fred");
or:
JTextField nameField = new JTextField("Fred", 10);
red foreground
blue foreground
contents
JFrame Container
JPanel
demo....
Constructor:
new JDialog(JFrame owner, boolean modal)
or JDialog
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
pack();
// Note: no call to setVisible
} // end constructor
try {
age = Integer.parseInt(ageText.trim());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,
"error: \"" + ageText +
"\" is not an integer");
return; // don't continue with actionPerformed
} // end try/catch
CISC 323 winter 2006, Swing 74
PersonDialog (4)
if (age < 0 || age > 150) {
JOptionPane.showMessageDialog(this,
"error: age must be between 0 and 150");
return;
} // end if
else {
JOptionPane.showMessageDialog(this,
"internal error: unknown button");
} // end if
} // end actionPerformed