Java Swing Overview A. O’Riordan, Nov., 2007 Includes notes by K. Brown, 2004-2007 What is Swing? • Swing widget toolkit for Java used for constructing a graphical user interface (GUI) - part of The Java Foundation Classes (JFC) • “Swing” was the codename of the project that developed the first JFC components • Swing improvement on earlier Abstract Window Toolkit (AWT) • AWT includes basic set of GUI widgets such as buttons, text boxes, and menus, several layout managers, core GUI event subsystem, and AWT Native Interface • JFC includes Pluggable Look and Feel; Accessibility; Java 2D (Java 2 onwards); Drag and Drop Swing Characteristics • • • • • • • Platform independent Extensible Component based Customizable Event driven Separates Component Model from View Lightweight • Demo – WebStart SwingSet – http://java.sun.com/products/javawebstart/demos.html Swing History 1996 1997 AWT part of Java from start Sun incorporates Netscape Communications's IFC (Internet Foundation Classes) with other technologies to form the Java Foundation Classes. 1998 Released as part of the Java Standard Edition release 1.2. 2002 Drag and drop added (release 1.4) 2004/6 Improvements in Java 5 and 6 • Much of the Swing API is generally a extension of the AWT rather than a direct replacement • At its core, every Swing component relies on an AWT container, since (Swing's) JComponent extends (AWT's) Container Swing Structure • Swing is large - learn general principles and design styles - then use the API reference • Java 6 API Reference available at: – http://java.sun.com/j2se/1.6.0/docs/api/ • Sun’s Swing tutorial – http://java.sun.com/docs/books/tutorial/uiswing/index.html • Swing, like the rest of the Java API, is subdivided into packages: – javax.swing – javax.accessibility – javax.swing.border … • Most Swing programs also need AWT packages – java.awt – java.awt.event Swing Overview • Swing applications consists of multiple parts – – – – Containers Components Events Graphics • Sun makes a distinction between lightweight and heavyweight components: – Lightweight components are not dependent on native peers to render themselves. They are coded in Java. – Heavyweight components are rendered by the host operating system. They are managed by the underlying window manager. Top-level Containers • At the root of every containment hierarchy • All Swing programs have at least one • Content panes - contains everything except menu bar for most Swing applications Types of top-level containers: • JFrame - Window with border, title and buttons • Dialogs – secondary window – More limited than frames – Types of dialogs – JOptionPane, ProgressMonitor, JColorChooser, JDialog • JApplet – requires Java plug-in for browser Panels/Panes – Intermediate-level Containers I • • • You don’t add (atomic) components such as buttons directly onto a top-level container such as a JFrame. Each top-level container has a content pane that contains visible components in that top-level container’s GUI. Add component to the content pane: JFrame frame = new JFrame("HelloWorld App"); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); Panels/Panes – Intermediate-level Containers II JPanel • Simplify the positioning of other components • Contains everything except menu bar for most Swing applications • A panel’s default layout manager is FlowLayout • Create as a separate class: MyPanel panel = new MyPanel(); frame.getContentPane().add(panel); JScrollPane; JTabbedPane • Allow interaction Create a Component • Created just like any class instance – JButton button_ok = new JButton(“OK”); • Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JColorChooser) • With an image: ImageIcon cup = new ImageIcon("images/cup.gif"); JButton button1 = new JButton("Java", cup); Some Types of Component • Buttons • Combo boxes • Lists • Menus • Sliders • Text Fields • Labels More Components • Tool tips • Progress bars • Colour choosers • File choosers • Tables • Text • Trees Basic Swing Components Basic Controls Simple components that are used primarily to get input from the user JButton JCheckBox JList JComboBox JSlider JRadioButton JMenu JSpinner JTextField Swing Component Hierarchy (image from here: http://www.particle.kth.se/~fmi/kurs/PhysicsSimulation/Images/7a/swingHierarchy.gif) Methods inherited by components … • customising appearance – get/set Border/Font/Background ... • affecting component state – enabling, making visible,... • • • • registering listeners displaying the component ("painting") adding and removing other components determining layout – get/set Layout/PreferredSize ... • absolute positioning – get/set Size/Location/Bounds ... Using a Component 1. 2. 3. 4. 5. Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it Event handling and listeners - three key bits of code: 1) add interface 2) register 3) handle Components can have multiple listeners All this for one button click ... Container (window) with component (button) Listener objects user user clicks button ae:ActionEvent event object is generated event is queued for action event dispatch loop: remove from queue, invoke handlers in registered listeners ... do something Types of Events AWT Event Hierarchy (from http://www.studyjava.org/exam/figevent.gif): EventObject’s Methods Events are represented as Objects Superclass of all event classes is java.util.EventObject Methods defined in EventObject class: • Object getSource() returns the object that originated the event - if the user clickes a button, the method getSource returns the object corresponding to button • int getID() returns the integer value corresponding to the type of event - e.g. if the user clickes mouse, method getID returns the integer defined as MouseEvent.MOUSE_CLICKED Component Listeners Global component listeners may be used for any components • • • • • ComponentListener (changes in size, position, visibility) FocusListener (whether ability for keyboard input) KeyListener (key press events, only with focus) MouseListener (clicks and movement into/out of component area) MouseMotionListener (changes in position over component) Component-specific listeners relevant to specific components • ActionListener, CaretListener, ChangeListener, DocumentListener, ItemListener, ListSelectionListener, WindowListener, etc. Example: WindowListener • the WindowListener interface specifies methods which respond to changes in a window's state: • windowActivated(...): window is set to be active • windowClosed(...): window is closed by program • windowClosing(...): window closed by user • windowDeactivated(...): window is no longer active • windowDeiconified(...): window is restored to normal • windowIconified(...): window is minimised • windowOpened(...): window opened for first time Listener as Inner Class • Listener as Inner Class (what we’ve done in all the examples so far) public class Gui{ public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(new MyWinListener()); //... private class MyWinListener extends WindowListener { public void windowClosing(WindowEvent we) { System.exit(0); } // etc. Anonymous Inner Class • Listener as Anonymous Inner Class – No class name frame.addWindowListener(new WindowListener(){ public void windowClosing(WindowEvent we) { System.exit(0); } //etc. } // end class definition GUI itself implementing Listener GUI implements listener itself: public class Gui implements WindowListener{ public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(this); //... public void windowClosing(WindowEvent we) { System.exit(0); } // etc. Pluggable Look and Feel (PLAF) • Import package javax.swing.plaf • Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities • Can use third party PLAF or create your own look and feel using the Synth package • Here are some utility functions that set the LAF to native, Java (Metal), and Motif, respectively: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); Look and Feel Example • Examples: Java, Windows, Motif respectively: Graphics class Java AWT Graphics - basic but usually enough Properties stored in Graphics object - Color, Font, etc Methods of Graphics can: • Draw shapes - lines, rectangles, 3D rectangles, round-edged rectangles, ovals, arcs, polygons, e.g. – drawImage; drawLine; drawOval; drawArc; drawRect – fillArc; fillOval; fillRect • Set or get properties, e.g. – setColor; setFont – getColor; getFont • Draw text - Draw string on screen as a graphic – drawString Java2D Java2D graphics: • • • • Extends the AWT graphics to provide much more, e.g. gradients, textures, etc. (package java.awt.Graphics2D ) Graphics2D class extends the Graphics class richer graphics, font, and image APIs enhanced colour definition and composition, hit detection on arbitrary geometric shapes and text, and a uniform rendering model for printers and display devices Painting Components • Each JComponent has method for drawing components: void paintComponent(Graphics g) • Every component in a GUI has an object of the class Graphics associated with it known as the graphics context. It holds info about the current output device (e.g. the screen), the current drawing colour, the current font, and the clip rectangle (i.e. the area that needs repainting). • Whenever the system invokes a component's paint method, it supplies the component's graphics context as a parameter. When is a component painted? System-triggered painting: the system requests painting: • • • when a component is first made visible when a component is resized by the user when a component has been damaged and needs repair Application-triggered painting : • • when a component's model is updated Call repaint() method - paints whole component & any others as needed repaint(int leftx,int lefty,int width,int height) - only repaints a specified area • Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched. Custom painting • define a subclass of some JComponent (e.g. a subclass of JPanel) • in your class definition, override paintComponent • always have the following as the first line in your definition of paintComponent super.paintComponent(g); • send messages to g, the graphics context, to get it to draw things for you Swing not covered • Lots more components – JInternalFrame, .JDesktopIcon, JLayeredPane, JMenuBar,, JPopupMenu, JProgressBar, JRootPane, JScrollBar, JScrollPane, JSeparator, JSpinner, JSplitPane, JTabbedPane, JTable, JTableHeader, JTextComponent, JToolBar, JToolTip, JTree, JViewport • • • • • • • • • • • • Swing Models - specify how the data and state of a Swing component are stored and retrieved Borders Threaded Applications Assistive Technology – support for voice interfaces, screen readers Internationalization and Localization Integrate with Desktop Focus Subsystem Key bindings Dialog Modality Printing Drag and Drop Undo Framework