Introduction to Java Swing
Evolution of Java GUI
• Java 1.0: AWT built in 30 days, and it shows
• Java 1.1: AWT significantly improved, but GUI not finished yet
• Java 2: Swing, very different, vastly improved
• This lecture covers Swing only
Swing vs. AWT
• AWT: heavyweight
• primitive components
• Swing: lightweight
• no native code, platform independent
• pluggable look and feel
• its components are drawn in an AWT canvas
• event handling done by AWT
• all components' name start with J*
Swing features
• Powerful and flexible components
• Pluggable look and feel
• Provides ways to change just about everything, but you must work to understand how
• javax.swing.*
Basic principles
•Graphical components• ex: frames, buttons, drawings, etc.
• class hierarchy
• Events and actions• ex: press a button, click the mouse, etc.
Principles
• Define the graphical components
• instance of the API classes
• Place them (layout management) in a container
• Define actions associated to events (listeners) and associate them to the graphical components: event-driven
Principles
• A Swing interface is a tree having as root a system object (heavyweight) - container:
• JFrame: normal system window
• JWindow: non decorated system window
• JDialog: dialog box
• JApplet: an applet display area within a browser window
• The root contains objects handled by Java (lightweight)
An example
system style, as JFrame is heavyweight
Swing style, as JButton is lightweight
The Swing components hierarchy
Top-level containers
JFrame
JDialog
JApplet
General-purpose containers
JPanel
JToolbar
JSplitPane
JScrollPane
JTabbedPane
Special-purpose containers
JLayeredPane JInternalFrames
Basic controls
JCheckListJRadioButton
JButton
JMenuJMenuItem
JList
Basic controls
JComboBox JTextField
JSlider
Uneditable information displays
JLabel
JProgressBar
JToolTip
Editable displays of formatted information
JTree JText JTable
JColorChooser JFileChooser
Classification of Swing components
• Top-Level Containers
• The components at the top of any Swing containment hierarchy.
• General-Purpose Containers
• Intermediate containers that can be used under many different circumstances.
• Special-Purpose Containers
• Intermediate containers that play specific roles in the UI.
• Basic Controls
• Atomic components that exist primarily to get input from the user; they generally also show simple state.
• Uneditable Information Displays
• Atomic components that exist solely to give the user information.
• Editable Displays of Formatted Information
• Atomic components that display highly formatted information that (if you choose) can be edited by the user.
JFrame
• Setting up a frame:
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• Adding a component to a frame:
frame.add(component);
• Lay the components according to some rules and make them visible:
frame.pack();
frame.setVisible(true);
The JButton class
• The most common interactor in GUI-based applications is an on-screen button.
JButton pushMeButton = new JButton("Push Me");
Event notification
• Clicking on a button generates an action event, which in turn invokes a call to a method in any listeners that are waiting for action events.
• Callback:
Component
Event
Listener
registers
generates notifies
Using text components• JTextComponent hierarchy
An example
The JTextField Class
• You can accept keyboard input in a user interface by using JTextField
• Provides the user with an area in which it is possible to enter a single line of text.
• JTextField MyTextField = new JTextField(columns);
• columns is the number of text columns assigned to the field.
• The space often appears larger than one might expect, because Java reserves space for the widest characters.
• You can get and set the string entered in a JTextField by calling the getText and setText methods.
• A JTextField generates an action event if the user presses the ENTER key in the field.
The JTextField Class
Event handling
• Every time the user types a character (KeyEvent) or pushes a mouse button (MouseEvent) etc., an event occurs:
• stores info about what button, mouse position, etc. • added to an event queue• events in the event queue are sent to the objects registered to
listen for them
• Any object can be notified of the event:
• implements the appropriate interface (ex: ActionListener)• registered as an event listener on the appropriate event source.
• Swing components can generate many kinds of events.
• Possible to register multiple listeners to a single component
Example of GUI eventsAct that results in the event
• User clicks a button, presses Return while typing in a text field, or chooses a menu item
• User closes a frame (main window)
• User presses a mouse button while the cursor is over a component
• User moves the mouse over a component
• Component becomes visible
• Component gets the keyboard focus
• Table or list selection changes
Listener
• ActionListener
• WindowListener
• MouseListener
• MouseMotionListener
• ComponentListener
• FocusListener
• ListSelectionListener
Java event model
• delegation (or forwarding) model
notify
notify
doAction(e1)
doAction(e2)
How to implement an event handler
• Implement and instantiate an event listener:
public class MyClass implements XXXListener {…}
MyClass l = new MyClass(…);
• Register the event listener as an listener on event source:
EventSource.addXXXListener(l) ;
• From now on, every time an event e occurs, the event source object will trigger the appropriate doXXXAction(e) from l.
• Threads and event handling: event-handling code executes in a single thread, the event-dispatching thread.
• Event handlers should execute very quickly. Otherwise, the program's perceived performance will be poor. If needing lengthy operation, starting up another thread
Events with a button• You specify the response to a button click by overriding the
definition of actionPerformed() with a new version that implements the correct actions for each button.
• If there is more than one button in the application, you need to be able to tell which one caused the event.
• There are two strategies for doing so:
1. Call getSource() on the event to obtain the button itself.
2. Call getActionCommand() on the event to get the action command string, which is initially set to the button label.
Layout management
• Components are placed on panel using a “layout manager” based on the order in which you add() the components
• Size, shape and placement quite different depending on layout manager
• Applet and application window size also affects layout
Layout management
• Use different layout managers to control the size and position of the components
• Setting the layout manager: JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
• Providing hints about a component:
• provide size hints: setMinimumSize(Dimension), setPreferredSize(..), setMaximumSize(..)
• provide alignment hints: setAllignmentX(float), setAlignmentY(float)
• Putting space between components:
• the layout manager: can specify hgap and vgap.
• putting invisible components
• empty border: best for components that have no default border, eg: JPanel, JLabel
Types of layouts
•FlowLayout
•BorderLayout
•GridLayout
•CardLayout
•GridBagLayout
•BoxLayout
•NullLayout
FlowLayout
• Components “flow” onto from left-to-right and top-to-bottom
• Components take on “normal” size
• Default for JPanel.
BorderLayout
• Container divided into five regions: West, North, East, South, Center.
• Default for JFrame.
GridLayout
• Organized in rows & columns
GridBagLayout• Flexible layout manager that aligns components
horizontally and vertically, without requiring that the components be the same size
• Quite a mess to program
• Must use GridBagConstraints
• You can accomplish a lot by combining other layout managers.
• To make it easier, Swing has BoxLayout
BoxLayout
• Place all components in a row or in a column.
• Much of the benefit of GridBagLayout without the pain
• Has helper class Box which uses BoxLayout and builds components for you
NullLayout
• Absolute positioning
• setLayout(null);
• Programmers are responsible for setting the size and position of each component via setBounds(x, y, width, height)
Painting with Graphics
• JComponent has a few methods that can be overridden in order to draw special things:
public void paintComponent(Graphics g){}
public void repaint();
• java.awt.Graphics - API allows drawing of:
• Text strings
• Geometry
• Bitmap (raster) images
Java 2D API• A uniform rendering model for display devices and printers
• A wide range of geometric primitives, such as curves, rectangles, and ellipses, as well as a mechanism for rendering virtually any geometric shape
• Mechanisms for performing hit detection on shapes, text, and images
• A compositing model that provides control over how overlapping objects are rendered
• Enhanced color support that facilitates color management
• Control of the quality of the rendering through the use of rendering hints
The Graphics class
• The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components
• All coordinates that appear as arguments to the methods of this Graphics object are considered relative to the translation origin of this Graphics object prior to the invocation of the method.
Drawing• A line:
public abstract void drawLine(int x1, int y1, int x2, int y2);
• An outlined rectangle:
public abstract void drawRect(int x, int y, int width, int height);
• A filled rectangle:
public abstract void fillRect(int x, int y, int width, int height);
• A rectangle with fill of the background color:
public abstract void clearRect(int x, int y, int width, int height);
• An Oval outline:
public abstract void drawOval(int x, int y, int width, int height);
• A filled oval
public abstract void fillOval(int x, int y, int width, int height);
• An outline of a polygon, where the x and y are arrays of coordinates:
public abstract void drawPolygon(int[] x, int[] y, int numEdges);
• A filled polygon, where the x and y are arrays of coordinates:
public abstract void fillPolygon(int[] x, int[] y, int numEdges);
How painting works1. background
2. custom painting
3. border
4. children