Vous êtes sur la page 1sur 44

Advanced Swing - Roadmap

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

GUI Fundamental concepts - Look


Component, Container, Layout
These are the 3 words related to the look of a Java GUI. Component: typically a screen element such as a button, label, text field or a combo box. Container: components are added to a container Layout: positioning of components within a container. This is where the Java GUI toolkit differs from most GUI toolkits. The various implementations of the Layout Manager are responsible for the position of components. This eliminates the problems associated with hard coding of UI element locations.

Copyright Objective Consulting

Intro to Java GUI 2

Component, Container, Layout


An example to clarify Components, Containers and Layout Managers.

Buttons in a container using GridLayout

A container with a label and a text field. The following slides will provide more detail via code snippets.

Copyright Objective Consulting

Intro to Java GUI 3

Component, Container, Layout

Buttons in a Container with Layout set to GridLayout


JPanel buttonPanel = new JPanel(); // a JPanel is-a Container buttonPanel.setLayout( new GridLayout(3, 4)); // set Layout for(int i=0; i < 10; i++) { String btnLabel = String.valueOf(i); JButton button = new JButton(btnLabel); buttonPanel.add(button); // add Component to Container }
Copyright Objective Consulting Intro to Java GUI 4

Component, Container, Layout


Buttons in a container using GridLayout A container with a label and a text field.

Both containers are inside an enclosing container.

They are nested within a top-level container which is a JFrame.


The result panel is in the bottom half. The button panel is in the top half.
// put them all together - JFrame uses BorderLayout by default Container c = theFrame.getContentPane(); // get the JFrames container c.add(resultPanel, BorderLayout.SOUTH); c.add(buttonPanel, BorderLayout.CENTER); // center takes up all remaining space
Copyright Objective Consulting Intro to Java GUI 5

Some Layout Managers


BorderLayout
North, East, West, South, Center/remainder

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

Layout Managers Examples


Previous example shows:
BorderLayout for overall container GridLayout for buttons FlowLayout in bottom panel

Next example is from Intro

Copyright Objective Consulting

Intro to Java GUI 7

Gui from Intro orderprojV6

BorderLayout, FlowLayout, and GridLayout


class CustomerDataPanel extends JPanel { this.setLayout(new GridLayout(6,2)); this.add(new JLabel("First Name:", JLabel.RIGHT)); this.add(firstNameTextField);
Copyright Objective Consulting

Intro to Java GUI 8

More examples
There are a more examples available in
The Intro package Suns Swing Tutorial Your Java books

Copyright Objective Consulting

Intro to Java GUI 9

Java GUI Toolkits


There are two GUI toolkits available in Java. The original toolkit is the Abstract Windowing Toolkit (AWT). The second GUI toolkit is 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 next section will clarify this from a historical perspective.
Copyright Objective Consulting Intro to Java GUI 10

Toolkit History - AWT - JDK 1.0


The original GUI class library introduced in Java 1.0 is the Abstract Windowing Toolkit (AWT). A key characteristics of the original AWT is that it utilizes native platform toolkit peers. This is known as the heavyweight model. On Windows a java.awt.Button appears and behaves like a Windows button. On Unix (X11/Motif) a java.awt.Button appears and behaves like a Motif button. Therefore the Java code was portable across platforms and the application had the native platform look. The peer UI elements such as buttons and scrollbars had different subtle behaviors. The Motif toolkit is not as rich as the Windows or MAC toolkits. There were also implementation bugs. Therefore, portable AWT GUI programs were limited to the lowest common denominator
Copyright Objective Consulting Intro to Java GUI 11

Toolkit History - AWT - JDK 1.1


In Java 1.1 a new event handling mechanism replaces the container based event framework from Java 1.0. More flexible and efficient. This is used by Swing programs. The new event framework is a publisher/subscriber model Listeners subscribe to events. Component publish events; Events sent to subscribed listener(s) Listeners and adapters use interfaces
package java.awt.event public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Copyright Objective Consulting

Intro to Java GUI 12

Toolkit History - Swing


Netscape creates the Internet Foundation Classes (IFC) in 1996. Sun and Netscape co-operate and evolve IFC into the JFC which includes the Swing GUI toolkit.

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

Additional set of components giving a richer toolkit

Copyright Objective Consulting

Intro to Java GUI 13

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 benefits of the lightweight approach are:


Rich set of UI elements can be developed. Less reliance on native platform mean less bugs. Supports pluggable look & feel.
Windows, Motif, Metal Can have the same look across different platforms. Can even switch the look at run-time.
Copyright Objective Consulting Intro to Java GUI 14

Swing Overview Swing Set Demo


The following slides gives you insight into the range of Swings capabilities and shows you the pluggable looks which are:
Windows, Motif, Metal/Java (and Mac on Mac PCs)

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

Intro to Java GUI 15

Swing Overview Swing Set Demo

Button demo Windows Look & Feel


Copyright Objective Consulting Intro to Java GUI 16

Swing Overview Swing Set Demo

File Chooser demo Windows Look & Feel


Copyright Objective Consulting Intro to Java GUI 17

Swing Overview Swing Set Demo

File Chooser demo Motif Look & Feel


Copyright Objective Consulting Intro to Java GUI 18

Swing Overview Swing Set Demo

File Chooser demo Java/Metal Look & Feel


Copyright Objective Consulting Intro to Java GUI 19

Java GUI Toolkit Summary


Components, Containers and Layout Managers define the framework & concept for the look of Java GUIs. Two GUI toolkits available in Java. AWT components rely on native peers therefore give native look.
This is known as the Heavyweight model. The package is java.awt

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

Swing Toolkit Hierarchy


We will now look at the Swing Toolkit from an inheritance point of view.

Copyright Objective Consulting

Intro to Java GUI 21

Inheritance Hierarchy of Some Components


Component Classes beginning with letter J are from package javax.swing. Other classes are from package java.awt. Button List Container

JComponent

Jcomponent is the root of the lightweight components. Therefore JComponent is a good


starting point in the API documentation.

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.

Copyright Objective Consulting

Intro to Java GUI 22

11

Inheritance Hierarchy of Key Containers


Component

Classes beginning with letter J are from package javax.swing. Other classes are from package java.awt.

Container

A JFrame is-a Container - Heavyweight A JPanel is-a Container - Lightweight

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.

Copyright Objective Consulting

Intro to Java GUI 23

Heavyweight Swing Containers


Heavyweight Swing Container javax.swing.JFrame javax.swing.JApplet javax.swing.JWindow javax.swing.JDialog Inherited From java.awt.Frame java.applet.Applet java.awt.Window java.awt.Dialog

A window is essentially a frame without a border nor a menu bar. Must dispose() of heavyweight containers when done.

Copyright Objective Consulting

Intro to Java GUI 24

12

The recipe for building a GUI


Ingredients
Top level containers, other containers (usually Jpanel), common layout managers, common widgets, event handling interface specific to the widget in use, inner classes

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

Event Handling The 3 steps


// Step 1 write the event handling routine which implements the listener

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

ActionListener x = new MyEventHandler();


// Step 3 register the event handler with the event publisher

JButton b = new JButton(Press Me); b.addActionListener(x); // register x as an ActionListener


Copyright Objective Consulting

Intro to Java GUI 27

Event Handling Implementing Listeners


In most cases you have a few options for the implementation of your listeners. (There are at least 4 approaches with variations thereof). The example that follows uses a named inner class. This is the suggested option since it provides the following benefits:
Inner class has access to all instance vars of the main class. Is clear and readable. Is extensible.
The listener can be registered and deregistered.

Copyright Objective Consulting

Intro to Java GUI 28

14

Events getting text from JTextField


public class MyGUI extends JFrame { JTextField tf = new JTextField(); ActionListener al = new MyTextFieldListener(); public static void main(String a[]) { } protected void guiSetup() { tf.addActionListener(al); } class MyTextFieldListener implements ActionListener { public void actionPerformed(ActionEvent e) { String str = tf.getText(); // now do something with the string } } }
Copyright Objective Consulting Intro to Java GUI 29

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

Swing Containers Containment Model


The Swing containment model has 2 major features:
Standard organization and policy to manage menu bars and glass panes, in addition to the child components they contain. Z-ordering of child components. It creates the abstraction of a front-to-back layering of child components. The Swing container model achieves flexibility and uniformity across all containers by using delegation (instead of inheritance). The duties of a top-level container are implemented by specialized classes. This implementation can be used by any container which relieves the containers of re-implementing the same abstraction/API/interface. Swing containers that use the containment model are sometimes known as Top-level containers.
Copyright Objective Consulting Intro to Java GUI 31

Swing Containers using Containment Model


Swing Container javax.swing.JFrame javax.swing.JApplet javax.swing.JWindow javax.swing.JDialog javax.swing.JInternalFrame Description Used as the outermost container of an application. Outermost container of Swing applets. Has no border or menu bar. Base class for Swing dialog boxes. A frame that can manage all the same elements of an outermost frame but used internally in an application.

JInternalFrame is a lightweight container so must be place inside a heavyweight container (JFrame).


Copyright Objective Consulting Intro to Java GUI 32

16

Swing Containers - JRootPane


The top-level containers delegate the containment duties to a specialized component which is the root pane. Each of the top-level containers maintain a reference to an instance of a root pane. The class that implements the root pane is javax.swing.JRootPane. The JRootPane in turns delegates various responsibilities to other specialized classes. The following diagram illustrates this.

Copyright Objective Consulting

Intro to Java GUI 33

JRootPane and its children

Copyright Objective Consulting

Intro to Java GUI 34

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

all mouse events and filters out unwanted events.

Copyright Objective Consulting

Intro to Java GUI 35

Swing Containers RootPane usage


When components are added to a top-level container they are added to the content pane of the root pane. There are 2 ways to do this.
class Example extends JFrame { public Example() { JRootPane rootPane = this.getRootPane(); Container contentPane = rootPane.getContentPane(); contentPane.add(new Label(Hi); } } OR public Example() { Container contentPane = this.getContentPane(); contentPane.add(new Label(Hi); }

Copyright Objective Consulting

Intro to Java GUI 36

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.

Copyright Objective Consulting

Intro to Java GUI 37

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.

Copyright Objective Consulting

Intro to Java GUI 38

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

Copyright Objective Consulting

Intro to Java GUI 39

Model-View-Controller
notifies when content changes

Model
read contents

View

update if content changed (typing in textfield)

Controller

visual only update (scrolling)

User interface event


Copyright Objective Consulting

Intro to Java GUI 40

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

Copyright Objective Consulting

Intro to Java GUI 41

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.

Copyright Objective Consulting

Intro to Java GUI 42

21

UI Delegate
JComponent
ui: Component UI

Component UI

Abstract Button

Button UI

JButton

Basic Button UI

Copyright Objective Consulting

Intro to Java GUI 43

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)

Copyright Objective Consulting

Intro to Java GUI 44

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)

Copyright Objective Consulting

Intro to Java GUI 45

Pluggable Look-and-Feel (L&f)


If you dont set the L&F then the default is the Java look and feel which is metal.

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

Setting System Look-and-Feel


public static void main(String args[]) { try { // Get LAF associated with platform that we are running on. String systemLAF = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(systemLAF); } catch(Exception e) { e.printStackTrace(); } .. }

Copyright Objective Consulting

Intro to Java GUI 47

Setting a specific L&F


If we want our application to always have a Motif or Windows look, regardless on the platform on which the app is running, then we can set the L&F passing passing the UI manager the string of the L&F class. The strings are:
com.sun.java.plaf.motif.MotifLookAndFeel com.sun.java.plaf.windows.WindowsLookAndFeel javax.swing.plaf.metal.MetalLookAndFeel String motifLAF = com.sun.java.plaf.motif.MotifLookAndFeel; UIManager.setLookAndFeel(motifLAF);
Copyright Objective Consulting Intro to Java GUI 48

24

Changing L&F at run-time


The PLAF even permits changing the L&F at runtime. You could have a menu or button that allows the user to select their preferred L&F.
String userSelectedLaf; // set it to one of the LAF class names when the user presses a button UIManager.setLookAndFeel(userSelectedLaf); SwingUtilities.updateComponentTreeUI(this); // this refers to the outermost component; usually a JFrame

Copyright Objective Consulting

Intro to Java GUI 49

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.

Copyright Objective Consulting

Intro to Java GUI 52

26

Swing Models partial list


Model Interface Name ButtonModel ComboBoxModel ListModel ListSelectionModel TableModel Document Description An abstraction that defines state for various buttons such as check boxes, radio buttons and normal buttons. Subinterface of ListModel, which adds the capability to specify one of the items as selected. Defines an ordered list of elements. An abstraction of a selection on a list and provide the capability to specify those elements that are selected. Defines a two-dimensional table of objects. A generalized document that contains various kinds of text.
Copyright Objective Consulting

Intro to Java GUI 53

Swing Models Implementations


Model Interface Name ButtonModel ListModel ListSelectionModel TableModel Document Partial or full implementing class DefaultButtonModel AbstractListModel DefaultListSelectionModel AbstractTableModel DefaultTableModel AbstractDocument, DefaultStyledDocument, PlainDocument

Copyright Objective Consulting

Intro to Java GUI 54

27

Model usage by component


Model Name ButtonModel ComboBoxModel ListModel ListSelectionModel TableModel TableColumnModel Document Used by these components AbstractButton, JMenu, ButtonGroup JComboBox JList JList, JTable JTable JTable, JTableHeader JTextField, JTextArea, JPasswordField, JTextPane

Copyright Objective Consulting

Intro to Java GUI 55

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.

Copyright Objective Consulting

Intro to Java GUI 56

28

Swing Models - Implementations


From the table titled Swing Models Implementations we note that classes implement either partially or fully the model interface. Model names with the pattern Abstract*Model partially implement the interface. We can subclass these and implement the additional required methods and extend the behavior as necessary for our application. In many cases Default models are provided and we can simply use those since they provide an adequate default implementation of the required behavior. We can also subclass and override the default models.
Copyright Objective Consulting Intro to Java GUI 57

Swing Models Usage


Note that in most of the simple cases we do not need to concern ourselves with the model. We use the methods defined by the component. These methods in turn delegate to the model. For example, to determine if an instance of a JMenuItem is armed.
boolean armed = myMenuItem.isArmed();

The menu item will invoke the isArmed() method on its ButtonModel.

Copyright Objective Consulting

Intro to Java GUI 58

29

Swing Models Usage


In more complex cases we need to interact with the model. In these cases we call the getModel() method of the component which will return a reference to the model.

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

Intro to Java GUI 59

Swing Models - JList


Note that JList is interesting because it uses 2 models.
The ListModel holds the values that are displayed by the JList. The ListSelectionModel is related to the items that are selected.

This will be discussed further when we look at the JList more closely.

Copyright Objective Consulting

Intro to Java GUI 60

30

Some Components

JScrollPane JTextArea JList

Copyright Objective Consulting

Intro to Java GUI 61

JScrollPane Purpose Basic Usage JTextArea examples


Problems & solutions

Scroll bars
Basics Problems & solutions
Copyright Objective Consulting

Intro to Java GUI 62

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.

Copyright Objective Consulting

Intro to Java GUI 63

JScrollPane Basic Usage


Add the component to be scrolled to the JScrollPane. Add the JScrollPane to the container.
textArea = new JTextArea(3, 20); . // To get scrolling add it to a scroll pane. scrollPane = new JScrollPane(textArea); // Add the scrollpane, not textArea, to container. Container contentPane = theFrame.getContentPane(); contentPane.add(scrollPane, BorderLayout.CENTER); // 3 rows,20 cols

Copyright Objective Consulting

Intro to Java GUI 64

32

JScrollPane Basic Usage


The component can be added to the JScrollPane either
via the constructor or later by adding to the viewport.
// Add textArea into scroll pane during construction. scrollPane = new JScrollPane(textArea); OR scrollPane = new JScrollPane(); scrollPane.getViewport().setView(textArea); OR scrollPane.getViewport().add(textArea,null);

Copyright Objective Consulting

Intro to Java GUI 65

JScrollPane JTextArea Example


JTextArea problem & solution
// By default text areas do not wrap. textArea.setLineWrap(true); textArea.setWrapStyleWord(true); // wrap a word boundaries

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

JScrollPane JTextArea Example


JTextArea problem & solution
I once wrote a message panel widget for a tic-tac-toe game and had problems getting it to display the last text appended to it. Solution was ..
public void addMessage(String txt) { textArea.append(txt); // Setting the caret at the end programmatically // was necessary. int pos = textArea.getText().length(); textArea.setCaretPosition(pos); }

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 Scrollbar Basics


Scrolling is required when the size of the data to be displayed is larger than the viewport. Scrollbars are displayed based on the Scrollbar Policy The default ScrollBarPolicy is that horizontal and vertical scrollbars appear whenever the component's contents are larger than the view. This is acceptable is most cases. The scrollbar policy can be explicitly set set either via the constructor or via the set*ScrollBarPolicy() methods.
scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_N EVER); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAY S);

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

Copyright Objective Consulting

Intro to Java GUI 69

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.

Copyright Objective Consulting

Intro to Java GUI 70

35

JScrollPane need more?


For more info refer to the JDK API for javax.swing.JScrollPane including the links to the Swing Tutorial.

Copyright Objective Consulting

Intro to Java GUI 71

Advanced Swing - JList Purpose Architecture Demo 1 Simple Usage Getting Selections Selection Modes Setting and Changing List Contents

Copyright Objective Consulting

Intro to Java GUI 72

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.

Copyright Objective Consulting

Intro to Java GUI 74

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

Copyright Objective Consulting

Intro to Java GUI 75

JList Getting the selection(s)


There are a number of methods for getting the selections but the most commonly used are:
Object Object[] getSelectedValue() Returns the first selected value, or null if the selection is empty. getSelectedValues() Returns an array of the values for the selected cells.

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.

Copyright Objective Consulting

Intro to Java GUI 77

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()); } }.

Copyright Objective Consulting

Intro to Java GUI 78

39

JList - ListSelectionListener
To register our ListSelectionListener we can register directly with the ListSelectionModel
ListSelectionModel lsm = jList1.getSelectionModel(). lsm.addListSelectionListener(new MyItemListener());

OR, better yet, use the method provided directly by JList


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

Copyright Objective Consulting

Intro to Java GUI 79

JList Selection Modes


The ListSelectionModel can be set to one of 3 modes. SINGLE_SELECTION
only 1 item can be selected

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.

Copyright Objective Consulting

Intro to Java GUI 80

40

JList Selection Modes


Since MULTIPLE_INTERVAL_SELECTION is the default lets see how to force SINGLE_SELECTION.
jList1.getSelectionModel().setSelectionMode(ListSelectionModel.SINGL E_SELECTION);

// OR use the method from JList that simply delegates


jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Copyright Objective Consulting

Intro to Java GUI 81

JList Changing the List contents


In the first example we saw how to set a fixed list of data.
String[] colors = { "blue", "red", "green", "yellow }; JList jList1 = new JList(colors);

Next we see will see


How to change the data to another fixed set of data using the JList setListData() method. How to use a dynamic set of data in which elements can be removed or added.

Copyright Objective Consulting

Intro to Java GUI 82

41

JList Changing the List contents


If you need to change the data to another fixed set of data use the JList setListData() method.
Object[] colors2; // a new set of colors

// colors2 gets populated jList1.setListData(colors2);

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

Intro to Java GUI 83

JList Dynamic List contents


If we have an application in which elements must be dynamically added or removed we must use a DefaultListModel.

The JLists view will update its appearance accordingly when elements are added or removed.

Copyright Objective Consulting

Intro to Java GUI 84

42

JList Dynamic List contents


Lets look at how we can make the right list dynamic.
JList rightList = new JList(new DefaultListModel()); // Handler for the add button int x = leftList.getSelectionModel().getMinSelectionIndex(); int y = leftList.getSelectionModel().getMaxSelectionIndex(); // Iterate over intervals and if an item is selected then add it to // the model on the right if the item is not already in the list. DefaultListModel dlm = (DefaultListModel)rightList.getModel(); for (int i=x; i<=y; i++) if (leftList.getSelectionModel().isSelectedIndex(i)) if (!dlm.contains(leftList.getModel().getElementAt(i))) dlm.addElement(leftList.getModel().getElementAt(i));
Copyright Objective Consulting

// Find the boundaries of the selection intervals (all intervals)

Intro to Java GUI 85

JList Changing the List contents


In the first example we saw how to set a fixed list of data. If you need to change the data to another fixed set of data use the JList setListData() method. This method essentially creates a new ListModel and sets its ListModel reference to that model. If you have the need to to add or remove the elements from the list, and have the Jlist component update its appearance accordingly, then you must create a DefaultListModel and tell the JList to use that model.
Copyright Objective Consulting Intro to Java GUI 86

43

JList - Summary
SUMMARY

Copyright Objective Consulting

Intro to Java GUI 87

Putting it all together


A Swing GUI for Remote File Viewer

Copyright Objective Consulting

Intro to Java GUI 88

44

Vous aimerez peut-être aussi