32
Java Swing Overview A. O’Riordan, Nov., 2007 Includes notes by K. Brown, 2004-2007

Java Swing Overview

  • Upload
    avital

  • View
    57

  • Download
    4

Embed Size (px)

DESCRIPTION

Java Swing Overview. 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) - PowerPoint PPT Presentation

Citation preview

Page 1: Java Swing Overview

Java Swing Overview

A. O’Riordan, Nov., 2007

Includes notes by K. Brown, 2004-2007

Page 2: Java Swing Overview

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

Page 3: Java Swing Overview

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

Page 4: Java Swing Overview

Swing History

1996 AWT part of Java from start

1997 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

Page 5: Java Swing Overview

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

Page 6: Java Swing Overview

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.

Page 7: Java Swing Overview

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

Page 8: Java Swing Overview

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);

Page 9: Java Swing Overview

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

Page 10: Java Swing Overview

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);

Page 11: Java Swing Overview

Some Types of Component

• Buttons

• Combo boxes

• Lists

• Menus

• Sliders

• Text Fields

• Labels

Page 12: Java Swing Overview

More Components

• Tool tips

• Progress bars

• Colour choosers

• File choosers

• Tables

• Text

• Trees

Page 13: Java Swing Overview

Basic Swing Components

Basic Controls Simple components that are used primarily to get input from the user

JButton

JCheckBox

JComboBox

JList

JMenu

JRadioButton

JSlider

JSpinner

JTextField

Page 14: Java Swing Overview

Swing Component Hierarchy

(image from here: http://www.particle.kth.se/~fmi/kurs/PhysicsSimulation/Images/7a/swingHierarchy.gif)

Page 15: Java Swing Overview

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 ...

Page 16: Java Swing Overview

Using a Component

1. Create it

2. Configure it

3. Add children (if container)

4. Add to parent (if not JFrame)

5. Listen to it

Event handling and listeners - three key bits of code:

1) add interface

2) register

3) handle

Components can have multiple listeners

Page 17: Java Swing Overview

Container (window) withcomponent (button)

All this for one button click ...

user

user clicksbutton

event objectis generated

ae:ActionEventevent isqueuedfor action

Listener objects

... do somethingevent dispatch

loop: remove fromqueue, invokehandlers in registered listeners

Page 18: Java Swing Overview

Types of Events

AWT Event Hierarchy (from http://www.studyjava.org/exam/figevent.gif):

Page 19: Java Swing Overview

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

Page 20: Java Swing Overview

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.

Page 21: Java Swing Overview

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

Page 22: Java Swing Overview

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.

Page 23: Java Swing Overview

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

Page 24: Java Swing Overview

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.

Page 25: Java Swing Overview

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");

Page 26: Java Swing Overview

Look and Feel Example

• Examples: Java, Windows, Motif respectively:

Page 27: Java Swing Overview

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

Page 28: Java Swing Overview

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

Page 29: Java Swing Overview

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.

Page 30: Java Swing Overview

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.

Page 31: Java Swing Overview

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

Page 32: Java Swing Overview

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