Académique Documents
Professionnel Documents
Culture Documents
We will see a blend of key concepts and some specific Swing components that you can use for the RMI File Viewer GUI. First we will begin with a review of key info from the Intro course and augment it. Then we will look at more details of Swing including some selected components such as JScrollPane and Jlist.
Copyright Objective Consulting Intro to Java GUI 1
A container with a label and a text field. The following slides will provide more detail via code snippets.
FlowLayout
Components left to right and then top to bottom.
GridLayout
Row and columns of equal sized components
CardLayout
Components laid out on top of each other
GridBag
Most complex but most control
BoxLayout
between Grid and GridBag in terms of capabilities and complexity.
Custom layout managers used by some GUI builders such as Jbuilder xyLayout Null
No layout manager. Components at fixed locations
Copyright Objective Consulting Intro to Java GUI 6
More examples
There are a more examples available in
The Intro package Suns Swing Tutorial Your Java books
Swing was introduced as an extension package in the 1.1 timeframe. As of Java 2.0 (since JDK 1.2) Swing is part of the Java platform (i.e. a standard package).
Swing introduced some new architecture and capabilities. Key items are: Lightweight components
this supports the Pluggable Look and Feel
Swing Overview
Lightweight Swing UI elements are painted onto the screen
Swing is not peer based for JComponents such as JButtons, JTextfields. Java code is used to draw/paint the JComponents into a heavyweight container. Relies on peer/native toolkit only to put up a window and provide mechanism to paint on it. (need 1 heavyweight component for app)
The capabilities of Swing are most easily demonstrated by using the Swing Set demo. The Swing Set demo is part of the demos that can be installed with the SDK. For example, with the demos installed as part of SDK 1.3 the swingset demo is installed at the following location. yourSDKdir\demo\jfc\SwingSet2 The readme file tells you how to run it as an application or applet. To run as as an application: java -jar SwingSet2.jar
Copyright Objective Consulting
The AWT components are used only in older applications and some applets. Swing is based on a Lightweight component model.
Swing Components such as JButton, JTextField are painted on the screen Swing supports a pluggable look & feel. The package is javax.swing
The UI elements such a Button, Text Fields, etc. used in todays applications are from the Swing toolkit. There is a common event handling framework used by both AWT and Swing applications. The package is java.awt.event
Copyright Objective Consulting Intro to Java GUI 20
10
JComponent
JButton
JList
JTextComponent
JComboBox
JTextField
JTextArea
JEditorPane
JButton, JTextField, JTextArea and JList are some of the concrete components the you will use in Swing applications.
11
Classes beginning with letter J are from package javax.swing. Other classes are from package java.awt.
Container
JComponent
Window
JPanel
Frame
JFrame
The JFrame is the top-level container used for Swing applications. The JPanel is used for containers nested inside the heavyweight container.
A window is essentially a frame without a border nor a menu bar. Must dispose() of heavyweight containers when done.
12
Step 1) Mock up the GUI Step 2) Decide how to slice up with various layout managers Step 3) Build from the bottom up or outside in
Try-bottom up first; more likely to write a re-usable component
Step 4) Write the event handling routine Step 5) Connect the event source to the event handling routine
Copyright Objective Consulting Intro to Java GUI 25
Event Handling
Publisher - subscriber event handling model A UI element publishes an event. The events is sent to all the registered listeners/subscribers. Example, when the user presses a button an Action event occurs. JButton generates an ActionEvent Therefore some object(s) must act as listener(s)/subscriber(s) and subscribe/register for notification of the event. For ActionEvents there is an interface/type named ActionListener. public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }
Copyright Objective Consulting Intro to Java GUI 26
13
class MyEventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(Button was pressed); } }
// Step 2 - create the event handler MyEventHandler is-a ActionListener
14
Advanced Swing
Top level containers and JRootPane Model View Controller View - UI Delegate Pluggable Look-And-Feel Swing Models Some Components
JScrollPane JTextArea JList
Copyright Objective Consulting Intro to Java GUI 30
15
16
17
Members of a JRootPane
Root pane member Layered pane Content pane Menu bar Glass pane Description Implements Z-ordering. By default it places all children in the content pane. Contains the children of the top-level container. (e.g. JButton, JTextField) Implements a menu bar. An invisible component that can be placed above all others. Used to block events targeted at the components of the layered pane. Typically a transparent JPanel registers for
18
Model-View-Controller
MVC is one of the most well known design patterns. Lets begin with two concrete examples. Imagine a spreadsheet.
The data that has been entered is the model. We can view the data/model as a table of rows and columns or we can view it as a pie chart.
Changing how we view the model does not change the content of the model.
If we are viewing large table then we may have to scroll. The controller sends the scrolling events so that the view is updated appropriately.
Model-View-Controller
Imagine an HTML document (example.html)
The HTML page is the model. The browser can render the page in the normal way (as a web page) or the browser can show us a view of the HTML source. We have at least two views of the document. Some HTML editors can have other views as well. If the page contains a link to another part of the page and we click on it then the browsers controller updates the view of the document which appears as if we have jumped to that section.
19
Model-View-Controller
Model: View: data a particular display of the data
Controller: handles events and sends them to the model and/or view
Model-View-Controller
notifies when content changes
Model
read contents
View
Controller
20
MVC in Swing
In practice the controller requires intimate knowledge of the view. Swing components implement a modified MVC design. The controller is integrated with the view. The view object acts as the controller.
View
Model
Controller
View UI delegate
Let us examine a JButton.
JButton btn = new JButton();
The button will have a model that keeps track of info such as whether or not the button is enabled. We know that lightweight Swing components support a Pluggable Look-and-Feel. The lightweight components delegate the job of rendering the component to an associated look-and-feel object. This object is the UI delegate. By changing the UI delegate the object can be rendered with a different look. The UI delegate is an instance of a javax.swing.plaf.ComponentUI. The next slide will clarify the architecture.
21
UI Delegate
JComponent
ui: Component UI
Component UI
Abstract Button
Button UI
JButton
Basic Button UI
UI Delegate
The previous UML diagram is used to illustrate that:
JComponents have-a ComponentUI (the UI Delegate). A concrete JComponent (e.g. JButton) will have-a concrete UI component (which is the UI delegate). By switching the UI component we can change the look (e.g. Metal, Windows, Motif)
22
UI Delegate
The previous UML diagram is used to illustrate that:
JComponents have-a ComponentUI (the UI Delegate). A concrete JComponent (e.g. JButton) will have-a concrete UI component (which is the UI delegate). By switching the UI component we can change the look (e.g. Metal, Windows, Motif)
Lets see how we can switch the L&F from the default (Metal on the left) to the L&F of the platform on which the application is running. If the application was running on Windows the L&F would be Windows (image on the right).
Copyright Objective Consulting Intro to Java GUI 46
23
24
Swing Models
The next few slides will give a partial list of the Swing model interfaces, model implementations, and usage by various swing components. This will help clarify the Model portion of MVC. We will begin by using button model to illustrate some key points.
The ButtonModel is used by a number of different components which of course have different visual representations such as Button, JMenuItem, JCheckBox, and JRadioButton.
Copyright Objective Consulting Intro to Java GUI 50
25
javax.swing.ButtonModel states
State Enabled Rollover Selected Armed Pressed Description The state in which the button can be selected or pressed. The state in which the mouse if positioned over the button. The state in which the button has been activated. The state in which the button has been pressed, but not activated. The state in which the user has pressed the mouse down on the button but not released it.
Copyright Objective Consulting Intro to Java GUI 51
javax.swing.ButtonModel
State Model for buttons. This model is used for check boxes and radio buttons, which are special kinds of buttons, as well as for normal buttons. For check boxes and radio buttons, pressing the mouse selects the button. For normal buttons, pressing the mouse "arms" the button. Releasing the mouse over the button then initiates a button press, firing its action event. Releasing the mouse elsewhere disarms the button. For more info, such as the list of methods, see the JDK API.
26
27
ButtonModel
From the previous tables we can see that
the abstraction defined by the button model interface relates to the management of state information the DefaultButtonModel is an implementation of the ButtonModel interface The ButtonModel is used by a number of different components such as Button, JMenuItem, JCheckBox, and JRadioButton.
28
The menu item will invoke the isArmed() method on its ButtonModel.
29
For example, for any instance of AbstractButton such as a JMenuItem or JButton we can retrieve the model then invoke methods defined by the model.
ButtonModel buttonMdl = myJButton.getModel(); // is mouse over the button? boolean b = buttonMdl.isRollOver();
Copyright Objective Consulting
This will be discussed further when we look at the JList more closely.
30
Some Components
Scroll bars
Basics Problems & solutions
Copyright Objective Consulting
31
JScrollPane - Purpose
In Swing scrolling is not performed by the JTextAreas and JList but by the JScrollPane component. If we examine the JDK docs and Swing tutorial for more overview one of the most important things to note is the concept of the viewport.
32
The complete source code for the example is in javaman.SwingEx8 found in the Intro source code.
Copyright Objective Consulting Intro to Java GUI 66
33
The complete source code for the example is in javaman.MessagePanel found in the Intro source code.
Copyright Objective Consulting Intro to Java GUI 67
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
Copyright Objective Consulting
is default
Intro to Java GUI 68
34
JScrollPane Scrollbars
Getting the scrollbars to initially appear
By default the scrollbars appear as needed. When the GUI is first rendered the amount of data in the client component may fit such that no scrollbars are required. However you may want scrollbars when the GUI is rendered. The reason for the problem and solution are described next. For clients that are not scroll-savvy (like JTextArea) the scroll pane computes its preferred size to the same as the client preferred size. Im as big as my client Since the preferred size of the JScrollPane is large enough to accommodate the preferred size of the client then no scrollbars are required.
JScrollPane Scrollbars
Getting the scrollbars to initially appear
One way to solve this problem is to set the size of the container housing the JScrollPane to be smaller than the preferred size of the JScrollPane(which is based on the preferred size of the client). An example of forcing scrollbars and more info is available in the Swing tutorial. Go to the JDK API doc for JScrollPane and you will find a link to the scroll pane section of tutorial. JListDemo1 on Phils website shows how forcing scrollbars to initially display was achieved by setting the preferred size of the client component (which is a JList). Note that the default # of rows for JList is 8.
35
Advanced Swing - JList Purpose Architecture Demo 1 Simple Usage Getting Selections Selection Modes Setting and Changing List Contents
36
JList - Purpose
When check boxes or radio buttons require too much space a JList is a good option. It allows the user to select one or more items from a list.
The JList is fairly complex so we will use a few examples and focus on the most common usage.
Copyright Objective Consulting Intro to Java GUI 73
JList - Architecture
Recall that a JList presents the view of a list of items. The JList contains 2 models.
The ListModel holds the values that are displayed by the JList. The ListSelectionModel keeps track of items that are selected.
37
JList Demo1
In cases simple cases we only need to be aware of the models. The JList provides methods that delegate to the models that it maintains. To create a list with a fixed set of info we can use the constructor that takes a list of Objects. JList takes care of creating the ListModel.
String[] colors = { "blue", "red", "green", "yellow }; JList jList1 = new JList(colors);
In the JListDemo1 we retrieve the selected item when the button is pressed. Then the value is displayed in a text field.
class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { theTextField.setText( (String)jList1.getSelectedValue()); } }
Copyright Objective Consulting Intro to Java GUI 76
38
JList - ListSelectionEvents
In the previous example we retrieved the selected value when a button is pressed. If we want to be notified when the user is interacting with the list, such as selecting an item, then we must listen to changes that occur to the ListSelectionModel. The event that is generated is a ListSelectionEvent. Therefore the listener we must implement is the ListSelectionListener interface. The valueChanged() method is called when any selection changes occur including the user is scrolling the mouse in multi-select cases. We normally only are interested when the user is finished therefore we wait until valueAdjusting is false.
JList ListSelectionListener
/** * Inner class to listen to list selections */ class MyItemListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) // user has released mouse theTextField.setText( (String)jList1.getSelectedValue()); } }.
39
JList - ListSelectionListener
To register our ListSelectionListener we can register directly with the ListSelectionModel
ListSelectionModel lsm = jList1.getSelectionModel(). lsm.addListSelectionListener(new MyItemListener());
If we register via the JList the the source of the event is the Jlist and not the ListSelectionModel. This can make the event handling easier to implement if the event handler is listening to multiple sources (i.e. you have a number of Jlists or other components, such as a JTable, that generate list selection events).
SINGLE_INTERVAL_SELECTION
one contiguous interval can be selected
MULTIPLE_INTERVAL_SELECTION
anything can be selected using the shift and Ctrl keys this is the default mode.
40
41
The setListData() method creates a new ListModel and sets the JList ListModel reference to the new model. This is the same things that occurs when the data is passed in via the constructor. In both cases we have a read-only view of the model. (see ListModel interface)
System.out.println(jList1.getModel().getElementAt(i));
Copyright Objective Consulting
The JLists view will update its appearance accordingly when elements are added or removed.
42
43
JList - Summary
SUMMARY
44