Swing tutorial notes
These are my notes from a tutorial on Swing given by Arun Rao, Digerati corporation, at Santa Clara University, June 6th, 1998. These notes are from the perspective of a Tcl/Tk programmer, so there are probably things here that are wonderful to a JDK 1.0/1.1 programmer, but not impressive to me -- eg the slide that says "images are finally easy." Having said that, Tcl/Tk has been stuck in its current state for a few years now, and I think that Swing and the Java 2D API have leapfrogged AWT past Tk.
Terminology
- MVC -- model-view-controller
- L&F -- Look and feel
- PLAF -- pluggable L&F
- JAF -- Java activation framework. Abstracts data-handling portion of the application. Able to support eg real-time streams.
Notes -- lecture 1
- Drag and drop framework work within same JVM, between different JVMs, and between a JVM and a native window. Actually a more general data transfer mechanism.
- Swing is entirely "light-weight" (peerless) components. (Too bad they're so damn slow...)
- Swing supported by major browsers now. Patches required to the VM to upgrade to 1.1.4.
java.sun.com/products/jfc/swingdoc-current- I asked if there was any major reason for the lack of performance which would be targeted in the promised performance improvements. Arun just said that it was young software and would be tuned. That wasn't the answer I was after.
- A component called NetCode developed a framework which was acquired by Netscape and dubbed IFC. Sun later joined forced with Netscape and produced JFC, which is "Sun's way of doing it."
- Swing currently has a 2-Meg footprint. When Swing is in the JVM, real applications will be around 300k. (Downloadable JAR size.)
- The Swing collection has Beans support, allowing highly-customizable interfaces. Someone asked if you could include, say, a video clip, and Arun said yes, but I don't get it.
- Swing does run on the Mac using Apples VM (licensed from Sun.) This was a comment from the audience. He didn't know if it runs on browsers on the Mac.
- Swing is based on MVC. Yada yada yada. Suddenly MVC is the flavour of the week. The magic of Java: twenty year old ideas (good ones) are suddenly in the common lingo. View-Controller combo manages visuals. Not all components need Models. Swing provides default Model implementations for most Components. You can replace the default models by implementing the appropriate interface.
- Light-weight components allow consistent look and feel across platforms. I queried this, since it goes against good practice.... Arun replied that the point is that you can code without regard for the platform you are running on. Good point.
- Someone asked why re-implementing L&F entirely in Java could be more efficient. Apparently the heavy traffic across the Java-C boundary, with appropriate conversion of data types, can be very inefficient.
- getContentPane must be used to get the pane to which you add things into top-level widgets (eg windows and applets).
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); ... getContentPane().setLayout(new FlowLayout()); button = new JButton(...); getContentPane().add(button);- Action is the superclass of Swing action listeners. It actually extends ActionListener, and allows icons and text strings to be associated with actions. It can have multiple controls -- eg for a button and a menu entry.
JButton saveButton = (JButton)tb.new(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { // .. implement save here } }(Is this legal?)- Focus manager manages focus; repaint manager manages repaints -- it optimizes redraw -- (I didn't ask but I assume that in (old) AWT you had to do damage regions yourself). Undo/redo support.
- BoxLayout give horizontal and vertical layout of components without wrapping. Box is a component that uses BoxLayout as its layout manager, and has a bunch of static methods that provide ready-to-use invisible containers that can be used with BoxLayout: glue (expands) as necessary, struts (which are rigid), and rigid areas (?).
- OverlayLayout provides "z-order". ViewportLayout seems to be like a 2d scroller, but Arun didn't actually know.
- Older layout manager still need to be used. Eg BorderLayout. AWT and Swing layout manager can be mixed freely (unlike the components themselves).
Notes -- lecture 2
- We started by looking at the SwingSet demo from Sun... Menus don't have to be attached to the top-level frame, but can be placed anywhere.
- You can implement a full desktop within the LayeredPane by using JInternalFrame. Like Frames and applets, JInternalFrame has a content frame. (In the Swingset demo, click on "Make" to produce a new internal frame.) Frames in each layer can be brought to the front of each other, but layers maintain their z-order (higher layer numbers go on top).
- The Table is very powerful -- I didn't realize before. It appears that the default CellRenderer, which the table uses to render the table, assumes that the items in the table are actually Swing components. (Arun was sort of vague on this, so this is my guess at how it works.) I assume therefore that if the model contained just data, you would write a CellRenderer that knew how to convert the data into Swing components.
- JComponent is the root of Swing components. Features: Borders, tooltips, double-buffering, debug graphics, keystroke handling, autoscrolling. Keystroke handling is simplified -- you register keys you are interested in with registerKeyboardAction, supplying a KeyStroke and an Action. There is apparently a powerful focus model that works together with keystrokes. There is also support for keyboard maps and accelerators keys.
- There are a bunch of border classes. You can create your own by extending AbstractBorder. BorderFactory provides predefined borders which are shared when possible. Empty borders are used to provide spacing.
- Autoscroll: JComponent.setAutoScrolls(true). Causes mouseDragged event every 100 ms while mouse is outside component (while dragging?). Must be contained in scrollable component like ViewPort.
- AbstractButton is base class of all buttons. "Complicated button hierarchy." Event support uses ActionListeners, ChangeListeners, and ItemListeners (eg for rollovers, other advanced features (?)). Separate text/icon for different button states. doClick simulates a "real" button press.
Notes -- Lecture 3
- All buttons have a model. ButtonGroup provides mutual exclusion (eg radiobuttons).
- Icons:
JMenuItem mi = new JMenuItem("New", new ImageIcon("images.new.jpg");- Alignment:
mi.setHorizontalAlignment(JMenuItem.LEFT);- Popups can be used anywhere:
c.addMouseListener(new MouseAdapter () { public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { menu.show(c,e.getX(), e.getY()); } } }- Layouts are possible with menus, for laying out items:
JPopupMenu menu = ni.getPopupMenu(); menu.setLayout(new GridLayout(3,2));- Light-weight or heavy-weight:
menu.setDefaultLightWeightPopuEnabled(false);- SplitPane manages two components in hor/vert split.
Manual control:setDividerLocation(int)
.
Movement controlled by:JComponent.setMinimumSize(...)
.
Continuous movement:setContinuousMovement()
.- Toplevel components (JFrame, JDialog, JWindow, JInternalWindow, JApplet) consist of a JRootPane only. A JRootPane contains a glassPane, an optional JMenubar, and a contentPane.
frame.getContentPane().add(child)- JFrame and JDialog are heavy-weight components that map to (native) peer. Modal dialogs cannot mix and match popup (JComboBox, JMenuBar, JPopupMenu) Swing and AWT components. (Limitation in JDK1.1.)
- Any kind of component can be added to LayeredPane. (JInternalFrame are the most commonly used.)
JComponent c = frame.getContentPane(); c.setLayoutManager(new BorderLayout()); c.add(new JButton(), BorderLayout.NORTH); ... ... frame.setLocation(new Point(100,100)); frame.show(); add(frame, JLayeredPane(DEFAULT_LAYER));- JTable is an extensible table with model/view separation and customizable editing and rendering. Attributes: resizable columns, autosizing, multiple cell selection, column reordering, cell editing, grid visibility, cell spacing. Table header is treated separately. Caution: logical column and physical column are different (because of reordering in view). There are TableModelListener and TableColumnModelListener (which handles reordering of the tables).
Note -- Lecture 4
- Text components are extensible by implementing an EditorKit and plaf.TextUI.
JTextComponent JTextField JTextArea JEditorPane JTextPaneplaf.TextUI builds view, sets colors, installs caret and keymap. EditorKit creates a model, view factory, edit commands, stream I/O. eg HTMLEditorKit, RTFEditorKit.
- JToolbar is floatable -- can be dragged into a separate window (setFloatable(true)). Warning: works best with BorderLayout. Can set separator, margins. Don't forget to use getComponent.
- JavaBeans... "reusable component that can be visually manipulated in a Builder tool." etc etc blah blah blah. All Swing components are JavaBeans.
- Multithreading. Swing is improved over AWT since it has centralized thread-related managers (RepaintManager, FocusManager). "Reasonably thread-safe." Ad-hoc fine-grained locking can yield races and deadlock -- use SwingUtilities.invokeLater.
- Accessibility: assistive technologies for people with visual/physical disabilities. Components must implement Accessible, which has the method getAccessibleContext. Built into foundation -- intrinsic keyboard navigation, and supports multiple devices, is extensible.
- Drag and Drop: JVM transfers by DataFlavor; JVM-native data mapping by FlavorMap. Anything that can be dragged implements the Transferable interface.
- Migrating. Insert a "J" in front of each component class name. Don't forget getContainer.
- Digerati's tool: Worktool. Unified workflow applications. Zero footprint thin client.
Notes related to Swing and the Diva canvas
- I'm still convinced that the Diva canvas should not by default make figures in Swing components. Apart from performance, I don't want to have to wait until I understand Swing until I can do anything useful. However, it should probably be able to integrate Swing components somehow. One way would be to make Figure back into an interface, and produce a SwingFigure class that implements Figure.
- EventDispatcher should have "fire" methods, a la Swing.
- Use repaint instead of damage? This seems to be how Swing does double-buffering.
- Use SwingUtilities.isMouseRightButton() etc.
- Create diva.canvas.swing package for Swing integration classes.
- The Diva kernel should use Swing components. For example, an infospace could be implemented using a TableModel, and a surface could use JTable to display the data. What does Diva add? The incremental support... JTree is similarly usable.
- Similarly, the other Diva types should be implemented in the same way as the Swing models and views. In particular, we need to define the GraphModel interface!
- What about beans? Are infospaces beans?
Miscellaneous notes
- Arun took quite a while to get going.... 20 minutes in we were still on the slides about his company. He said "this isn't a plug." Huh.
- The seminar got much better after the first lecture, once he warmed up a bit.
- Books to buy: Larman -- UML; Ameraal -- graphics in Java; Orfali and Harkey -- new edition of Java/Corba. Also buy the other Swing book.
- I need to get at least one more battery: two don't last for a full-day seminar.