Professional Documents
Culture Documents
Java Swing: Chris North cs3724: HCI
Java Swing: Chris North cs3724: HCI
Chris North
cs3724: HCI
AWT to Swing
• AWT: Abstract Windowing Toolkit
• import java.awt.*
• Swing: new with Java2
• import javax.swing.*
• Extends AWT
• Tons o’ new improved components
• Standard dialog boxes, tooltips, …
• Look-and-feel, skins
• Event listeners
• API:
• http://java.sun.com/j2se/1.3/docs/api/index.html
Swing Set Demo
J2sdk/demo/jfc/SwingSet2
• Many predefined
GUI components
GUI Component API
• Java: GUI component = class
• Properties
•
JButton
• Methods
•
• Events
•
Using a GUI Component
1. Create it
• Instantiate object: b = new JButton(“press me”);
2. Configure it
• Properties: b.text = “press me”; [avoided in java]
• Methods: b.setText(“press me”);
3. Add it
• panel.add(b);
4. Listen to it JButton
• Events: Listeners
Anatomy of an Application GUI
GUI Internal structure
JFrame JFrame
JPanel containers
JPanel
JButton
JButton JLabel
JLabel
Using a GUI Component 2
1. Create it
2. Configure it order
3. Add children (if container) important
4. Add to parent (if not JFrame)
5. Listen to it
Build from bottom up
• Create: Listener
• Frame
• Panel
JLabel JButton
• Components
• Listeners
• Add: (bottom up)
JPanel
• listeners into components
• components into panel
• panel into frame
JFrame
Code
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);
f.show();
press me
Application Code
import javax.swing.*;
class hello {
public static void main(String[] args){
JFrame f = new JFrame(“title”);
JPanel p = new JPanel();
JButton b = new JButton(“press me”);
f.show();
} press me
}
Layout Managers
• Automatically control placement of components
in a panel
• Why?
•
Layout Manager Heuristics
null FlowLayout GridLayout
none,
Left to right,
programmer
Top to bottom
sets x,y,w,h
s
Combinations
JButton JButton
JTextArea
Combinations
JButton JButton
JFrame
n JPanel: FlowLayout
JPanel: BorderLayout
c
JTextArea
Code: null layout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);
p.setLayout(L);
p.add(b1);
p.add(b2); press me then me
f.setContentPane(p);
import javax.swing.*;
• init( ) - initialization
• start( ) - resume processing (e.g. animations)
• stop( ) - pause
• destroy( ) - cleanup
• paint( ) - redraw stuff (‘expose’ event)
Application + Applet
import javax.swing.*;