Swing Advanced HCI (IAT 351) TA: Syavash Nobarany
Swing & AWT AWT: Abstract Windowing Toolkit Swing: new with Java2 import java.awt.* Swing: new with Java2 import javax.swing.* Extends AWT Tons o’ new improved components
Partial AWT and Swing Class Hierarchy java.lang.Object CheckboxGroup Component MenuComponent Button Canvas Checkbox Choice Container Label List Scrollbar TextComponent JComponent Scrollpane Panel Window AbstractButton JLabel JList JPanel JScrollpane Applet Dialog Frame JButton JApplet JDialog JFrame java.awt.* javax.swing.*
Swing Features Pluggable look and feel Accessibility API: for people with disabilities Undo Framework API: supports unlimited numbers of actions to undo and redo Flexible Deployment: run within a browser as an applet or Java Web Start CDE/Motif Windows Metal
Swing Set Demo J2sdk/demo/jfc/SwingSet3
GUI Component API Java: GUI component = class Properties Methods Events JButton
Using a GUI Component Create it Configure it Add it Listen to it Instantiate object: b = new JButton(“press me”); Configure it Properties: b.text = “press me”; [avoided in java] Methods: b.setText(“press me”); Add it panel.add(b); Listen to it Events: Listeners JButton
Event-Driven UIs Old model (e.g., UNIX shell, DOS) Interaction controlled by system, user queried for input when needed by system Event-Driven Interfaces (e.g., GUIs) Interaction controlled by user System waits for user actions and then reacts More complicated programming and architecture
Event Dispatch Loop Event Queue Event Loop (runs in dedicated thread) Queue of input events Event Loop (runs in dedicated thread) Remove next event from queue Determine event type Find proper component(s) Invoke callbacks on components Repeat, or wait until event arrives Mouse moved (t0,x,y) Component Invoked callback method Update application state Request repaint, if needed
Event Dispatch Window Panel Label TextArea Panel Button Button Event Queue Mouse moved (t0,x,y) Mouse pressed (t1,x,y,1) Mouse dragged (t2,x,y,1) Key typed (t3, ‘F1’) … (queues and dispatches incoming events in a dedicated thread) Window Panel Label TextArea Panel /* callback for TextArea */ public void mouseMoved(e) { // process mouse moved event } Button Button
Events, Listeners, Adapters and Handler Methods Listener / Adapter Handler Methods ActionEvent ActionListener actionPerformed AdjustmentEvent AdjustmentListener adjustmentValueChanged MouseEvent MouseListener MouseAdapter mouseClicked mouseEntered mouseExited mousePressed mouseReleased KeyEvent KeyListener KeyAdapter keyPressed keyReleased keyTyped ComponentEvent ComponentListener ComponentAdapter componentShown componentHidden componentMoved componentResized Adapter classes with empty methods for Listener interfaces with >1 methods
Anatomy of an Application GUI Internal structure GUI JFrame JFrame JPanel containers JPanel JButton JButton JLabel JLabel
Using a GUI Component Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it order important
Build from bottom up Create: Add: (bottom up) Frame Panel Components Listener Create: Frame Panel Components Listeners Add: (bottom up) listeners into components components into panel panel into frame JButton JLabel JPanel JFrame
How does HelloWorld look like? class HelloButtonListener implements ActionListener { private JButton button; HelloButtonListener(JButton b){ button = b; } public void actionPerformed(ActionEvent e){ button.setText("Hello World!"); import java.awt.event.*; import javax.swing.*; public class HelloAgain extends JFrame { HelloAgain(){ super("Example: Swing GUI"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JButton b = new JButton("Show message!"); b.addActionListener(new HelloButtonListener(b)); add(b); setSize(250,100); } public static void main(String[] args){ new HelloAgain().setVisible(true); ActionEvent Mouse click
Keyword “super” A method that overrides a superclass's method Invoke the overridden method using “super” Example: public class Library extends AbstractLibrary { @Override public void printAddress() { super.printAddress(); // calls AbstractLibrary’s printAddress System.out.println(address); } …
Layout Managers A layout manager helps in arranging the components in a container Each layout manager: Encapsulates an algorithm for positioning and sizing of components Automatically calculates the coordinates of each component it manages If a container is resized, the layout manager readjusts the placement of the components
Layout Manager Heuristics null FlowLayout none, programmer sets x,y,w,h Left to right, Top to bottom BorderLayout GridLayout n c w e s
null layout JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null); // x,y layout p.add(b); f.setContentPane(p); press me
BorderLayout Allows placing of components by using the geographic terms: CENTER EAST NORTH SOUTH WEST The components are placed around the edges The component in the center uses the remaining space import java.awt.*; import java.swing.*; import java.awt.event.*; class BorderExample extends JFrame { BorderExample() { super("Example: BorderLayout"); setLayout(new BorderLayout()); add(new Button("Center"),BorderLayout.CENTER); add(new Button("East"),BorderLayout.EAST); add(new Button("North"),BorderLayout.NORTH); add(new Button("South"),BorderLayout.SOUTH); add(new Button("West"),BorderLayout.WEST); setSize(200,200); } public static void main(String[] args) new BorderExample().setVisible(true);
GridLayout Automatically arranges components in a grid of rows and columns The container is divided into equal-sized cells, and one component is placed in each cell import java.awt.*; import java.swing.*; import java.awt.event.*; class GridExample extends JFrame { GridExample() { super("Example: GridLayout"); setLayout(new GridLayout(2,2)); add(new Button("1,1")); add(new Button("1,2")); add(new Button("2,1")); add(new Button("2,2")); setSize(250,100); } public static void main(String[] args) new GridExample().setVisible(true);
FlowLayout Set layout mgr before adding components press me then me JFrame f = new JFrame(“title”); JPanel p = new JPanel( ); FlowLayout L = new FlowLayout( ); JButton b1 = new JButton(“press me”); JButton b2 = new JButton(“then me”); p.setLayout(L); p.add(b1); p.add(b2); Set layout mgr before adding components press me then me
Combinations JButton JButton JTextArea
Combinations JButton JButton JFrame n JPanel: BorderLayout c JPanel: FlowLayout JTextArea
Menu, MenuBar and MenuItem import java.awt.*; import java.awt.event.*; import java.swing.*; class MenuExample extends JFrame { MenuExample(){ super("Example: MenuBar"); final MenuBar mb = new MenuBar(); setMenuBar(mb); final Menu m = new Menu("File"); MenuItem mi; mi = new MenuItem("Exit"); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ System.exit(0); } }); m.add(mi); mb.add(m); setSize(250,100); public static void main(String[] args){ new MenuExample().setVisible(true); A frame may contain a menu bar with options When the mouse is clicked on an option a drop down menu appears Each menu consists of one or more menu items
JOptionPane Examples
JPanel Panel is the simplest container class import java.swing.*; import java.awt.event.*; class PanelExample extends JFrame { PanelExample(){ super("Example: Panel"); final Panel p = new JPanel(); p.add(new JButton("1")); p.add(new JButton("2")); p.add(new JButton("3")); add(p); setSize(250,100); } public static void main(String[] args){ new PanelExample().setVisible(true); Panel is the simplest container class A panel provides space in which an application can attach any other component, including other panels The default layout manager for a panel is the FlowLayout manager
Swing Architecture 2 important cases Features of a good system architecture: Easy to Understand Change Debug Reuse Design Principle: Reduced coupling 2 important cases View form Logic/Model Model from Database
Separating View from Logic/Model Model-View-Controller pattern Provides for a good way to partition work and create a modular design MVC components Model Data storage, no presentation elements View No data storage, presentation elements Controller Glue to tie the model and the view together
Modified MVC in Swing JList contains the visual properties ListModel: Contains the data in the list JList UI Manager List Model List UI
Applets JApplet is like a JFrame Already has a panel Access panel with JApplet.getContentPane( ) import javax.swing.*; class hello extends JApplet { public void init(){ JButton b = new JButton(“press me”); getContentPane().add(b); } contentPane JButton
Applet Methods Called by browser: init( ) - initialization start( ) - resume processing (e.g. animations) stop( ) - pause destroy( ) - cleanup paint( ) - redraw stuff (‘expose’ event)
Application + Applet Command line Browser JFrame or JApplet import javax.swing.*; class helloApp { public static void main(String[] args){ // create Frame and put my mainPanel in it JFrame f = new JFrame(“title”); mainPanel p = new mainPanel(); f.setContentPane(p); f.show(); } class helloApplet extends JApplet { public void init(){ // put my mainPanel in the Applet getContentPane().add(p); // my main GUI is in here: class mainPanel extends JPanel { mainPanel(){ setLayout(new FlowLayout()); JButton b = new JButton(“press me”); add(b); Command line Browser JFrame or JApplet contentPane JPanel JButton
Thank you