Java UI Toolkits: Some History

n AWT (Abstract Windowing Toolkit) Lecture 19: n Java adapters for Win/MacOS/Motif widgets n , aka JFC (Java Foundation Classes)

GUI Programming in Java n Widgets are reimplemented in pure Java n Still uses AWT for layout, events, & drawing n You need both AWT and Swing: 6.170 Lab in Software Engineering import java.awt.*; October 23, 2002 import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*;

Basic Widgets Attach Listeners to Widgets

JTextField JLabel JTextArea JButton b = new JButton (“Beep”); b.addActionListener (new BeepAction ()); JToolBar JList JComboBox class BeepAction implements ActionListener { JCheckBox public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit ().beep (); JRadioButton } (+ButtonGroup) JButton } JProgressBar

Anonymous Classes Various Kinds of Listeners required! n ActionListener JButton b = new JButton (“Beep”); void actionPerformed (ActionEvent e); b.addActionListener (new ActionListener () { n fired by all buttons, items, JComboBox, public void actionPerformed(ActionEvent e) JTextField (on Enter key) { Toolkit.getDefaultToolkit ().beep (); n ItemListener } void itemStateChanged (ItemEvent e); }); n fired by JCheckBox, JRadioButton, JComboBox

n ListSelectionListener n Java compiler generates a name for the void valueChanged (ListSelectionEvent e);

anonymous class, e.g. MyWindow$7 n fired by JList, JTable

1 Basic Containers Using Containers

n For structured containers, just add components JScrollPane scroller = new JScrollPane (); scroller.add (new JTextArea ()); JSplitPane splitter = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT); JPanel JScrollPane splitter.setLeftComponent (new JTree ()); splitter.setRightComponent (scroller); JTabbedPane tabs = new JTabbedPane (); tabs.add (“File Browser”, splitter); tabs.add (“Spreadsheet”, new JTable ());

n Unstructured containers (JPanel) need layout manager

JTabbedPane JSplitPane

Layout Managers Layout Adjusts to Space Available

n Layout manager sets the sizes and

positions of components in a container NORTH n Example: BorderLayout JComponent , list, status = ...; CENTER JPanel panel = new JPanel (); panel.setLayout (new BorderLayout ()); panel.add (toolbar, BorderLayout.NORTH); SOUTH panel.add (list, BorderLayout.CENTER); panel.add (status, BorderLayout.SOUTH); NORTH (toolbar) WEST (-) CENTER (list) EAST (-) SOUTH (status)

Visual Guide to Layout Managers Choosing A Layout Manager BorderLayout GridBagLayout n BorderLayout: good for main windows n e.g., toolbar N, main pane CENTER, S n BoxLayout: multi-purpose n Use nested panels to lay out arrays of widgets n Look at Box (JPanel with BoxLayout included) n FlowLayout: mostly useless n Horizontal BoxLayout is better for most purposes n GridLayout: good for uniform arrays n But stick to 1D (1xN or Mx1), not 2D (MxN) n GridBagLayout: the most powerful n It’s the only way to align a nonuniform array of labels and widgets both vertically and horizontally FlowLayout BoxLayout GridLayout n Painful to use; see Swing tutorial for examples

2 Loosen Up Your Layout Windows: Top-level Containers n Any Swing component may have a border JButton b = new JButton (“Beep”); JWindow JFrame JDialog b.setBorder (new EmptyBorder (5,5,5,5));

n Even better: b.setBorder(BorderFactory.createEmptyBorder n Ignore JWindow; use JFrame & JDialog (5,5,5,5)); n Can’t put in any other container n Other Border classes exist too (e.g. Etched, n Can’t add widgets directly to window Beveled, Titled), but less is more n Call getContentPane() to get a container

Standard Window Idioms Frames Can Have Menu Bars n Create window JFrame f = new JFrame (“My Program”); JMenuBar n Add widgets to its content pane Container content = f.getContentPane (); content.setLayout(...); JMenu content.add(...); n Set its behavior when user closes it JMenuItem f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // calls System.exit. Use only for main window! n Run layout and make window appear f.pack (); n JMenuBar and JMenu are containers f.setVisible (true); n Attach ActionListeners to JMenuItems n Destroy window when you’re done with it f.dispose (); // not needed with EXIT_ON_CLOSE n is separate from content pane

Dialog Boxes Periodic Tasks

n JDialogs can be modal or modeless n Use a timer to run a periodic task n Modal = user can’t click on main window

n JOptionPane provides simple modal dialogs import javax.swing.Timer; // not java.util.Timer! n showMessageDialog for error & info messages: JOptionPane.showMessageDialog Timer t = new Timer (1000 /* milliseconds */, (mainWindowFrame, new ActionListener () { “Can’t open file “ + filename, public void actionPerformed(ActionEvent e) { “Error Opening File”, autoSave (); JOptionPane.ERROR_MESSAGE); } n showConfirmDialog for yes/no/cancel or OK/cancel }); questions t.start (); // repeats every 1s until stopped n showInputDialog for one-line input with OK/cancel

3 Background Tasks Background Tasks in Swing n Timer task must be brief, because the user n Create a SwingWorker to run the task interface is frozen while it runs n construct() runs in background thread n Long-running tasks (both automatic and user- n Can’t access UI objects; mutable data shared with invoked) belong in a separate thread main thread must be protected by synchronization n Programming with multiple threads is tricky n finished() runs in main thread

because of race conditions n Applies the results of construct() to the UI

n While one thread is mutating an object (rep n Not in Java library, but in Swing tutorial invariant is temporarily invalid), another thread tries to look at the object (boom! broken rep) n Warnings

n Generally solved with synchronization, but this is n Multiple threads can have nasty bugs beyond the scope of 6.170. However... n QuoteServer is not thread-safe

Other Stuff Hints on Code Organization n Icons & images n Class for every window or

n Don’t bother – labels often work better class PokerGame extends JFrame {...}

n It’s hard to draw effective icons n Classes for reusable panels

n Look on web for public-domain collections class HandDisplay extends JPanel {...} (or Sun’s repository in references) n Factory methods for parts of a window n Painting JComponent makeBookmarkPane () {...}

n Don’t bother yet (but it will be necessary n Private fields for anonymous listeners for final project) private final ActionListener saveAction

n Encapsulate painting in a new widget = new ActionListener () {...};

Further Reading Other Java UI Toolkits n Swing Tutorial n IBM SWT (Standard ) n http://www.eclipse.org n http://java.sun.com/docs/books/tutorial/ uiswing/ n Platform-specific widgets where available, pure Java emulation where necessary n Java Look & Feel Graphics Repository n subArctic n http://developer.java.sun.com/developer/ n http://www.cc.gatech.edu/gvu/ui/sub_arctic/ techDocs/hi/repository/ n Constraint propagation, animation, output effects n These icons are not in the public domain – n Jazz see the site for licensing details n http://www.cs.umd.edu/hcil/jazz/

n Zoomable interfaces

4