Swing Advanced
-
Upload
akhil-ravichandran -
Category
Documents
-
view
253 -
download
2
Transcript of Swing Advanced
1
Copyright© Objective Consulting Intro to Java – GUI 1
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 2
GUI Fundamental concepts - LookComponent, 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.
2
Copyright© Objective Consulting Intro to Java – GUI 3
Component, Container, Layout
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.
An example to clarify Components, Containers and Layout Managers.
Copyright© Objective Consulting Intro to Java – GUI 4
Component, Container, Layout
• Buttons in a Container with Layout set to GridLayout
JPanel buttonPanel = new JPanel(); // a JPanel is-a ContainerbuttonPanel.setLayout( new GridLayout(3, 4)); // set Layoutfor(int i=0; i < 10; i++) {
String btnLabel = String.valueOf(i);JButton button = new JButton(btnLabel);buttonPanel.add(button); // add Component to Container
}
3
Copyright© Objective Consulting Intro to Java – GUI 5
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 defaultContainer c = theFrame.getContentPane(); // get the JFrame’s “container”c.add(resultPanel, BorderLayout.SOUTH);c.add(buttonPanel, BorderLayout.CENTER); // center takes up all remaining space
Copyright© Objective Consulting Intro to Java – GUI 6
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
4
Copyright© Objective Consulting Intro to Java – GUI 7
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 8
Gui from Intro – orderprojV6
• BorderLayout, FlowLayout, and GridLayoutclass CustomerDataPanel extends JPanel {
this.setLayout(new GridLayout(6,2));
this.add(new JLabel("First Name:", JLabel.RIGHT));
this.add(firstNameTextField);
5
Copyright© Objective Consulting Intro to Java – GUI 9
More examples• There are a more examples available in
– The Intro package
– Sun’s Swing Tutorial
– Your Java books
Copyright© Objective Consulting Intro to Java – GUI 10
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 today’s 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.
6
Copyright© Objective Consulting Intro to Java – GUI 11
Toolkit History - AWT - JDK 1.0The 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 12
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);
}
7
Copyright© Objective Consulting Intro to Java – GUI 13
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 14
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.
8
Copyright© Objective Consulting Intro to Java – GUI 15
Swing Overview – Swing Set Demo• The following slides gives you insight into the range of Swing’s
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 canbe 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 16
Swing Overview – Swing Set Demo
Button demo – Windows Look & Feel
9
Copyright© Objective Consulting Intro to Java – GUI 17
Swing Overview – Swing Set Demo
File Chooser demo – Windows Look & Feel
Copyright© Objective Consulting Intro to Java – GUI 18
Swing Overview – Swing Set Demo
File Chooser demo – Motif Look & Feel
10
Copyright© Objective Consulting Intro to Java – GUI 19
Swing Overview – Swing Set Demo
File Chooser demo – Java/Metal Look & Feel
Copyright© Objective Consulting Intro to Java – GUI 20
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 today’sapplications 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
11
Copyright© Objective Consulting Intro to Java – GUI 21
Swing Toolkit Hierarchy• We will now look at the Swing Toolkit from an
inheritance point of view.
Copyright© Objective Consulting Intro to Java – GUI 22
Inheritance Hierarchy of Some Components
Container
JComboBoxJTextComponent
JComponent
JList
Classes beginning with letter J are frompackage javax.swing.
Other classes are from package java.awt.
Component
JButton
JButton, JTextField, JTextArea and JList are some of the concrete components the you will use in Swing applications.
ListButton
JTextField JTextArea JEditorPane
Jcomponent is the root of the lightweight components. Therefore JComponent is a good starting point in the API documentation.
12
Copyright© Objective Consulting Intro to Java – GUI 23
Inheritance Hierarchy of Key Containers
Container
JFrame
Frame
JComponent Window
Classes beginning with letter J are frompackage javax.swing.
Other classes are from package java.awt.
A JFrame is-a Container - HeavyweightA JPanel is-a Container - Lightweight
Component
JPanel
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 24
Heavyweight Swing Containers
java.awt.Dialogjavax.swing.JDialog
java.awt.Windowjavax.swing.JWindow
java.applet.Applet javax.swing.JApplet
java.awt.Framejavax.swing.JFrame
Inherited FromHeavyweight Swing Container
•A window is essentially a frame without a border nor a menu bar.•Must dispose() of heavyweight containers when done.
13
Copyright© Objective Consulting Intro to Java – GUI 25
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 GUIStep 2) Decide how to slice up with various layout
managersStep 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 routineStep 5) Connect the event source to the event
handling routine
Copyright© Objective Consulting Intro to Java – GUI 26
Event HandlingPublisher - 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);
}
14
Copyright© Objective Consulting Intro to Java – GUI 27
Event Handling – The 3 steps// Step 1 – write the event handling “routine” which implements the listenerclass MyEventHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {System.out.println(“Button was pressed”);
}}
// Step 2 - create the event handler – MyEventHandler is-a ActionListenerActionListener x = new MyEventHandler();
// Step 3 – register the event handler with the event publisherJButton b = new JButton(“Press Me”);b.addActionListener(x); // register x as an ActionListener
Copyright© Objective Consulting Intro to Java – GUI 28
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.
15
Copyright© Objective Consulting Intro to Java – GUI 29
Events – getting text from JTextFieldpublic 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 30
Advanced Swing• Top level containers and JRootPane• Model View Controller• View - UI Delegate• Pluggable Look-And-Feel• Swing Models• Some Components
– JScrollPane– JTextArea– JList
16
Copyright© Objective Consulting Intro to Java – GUI 31
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 32
Swing Containers using Containment Model
Base class for Swing dialog boxes.javax.swing.JDialog
A frame that can manage all the same elements of an outermost frame but used internally in an application.
javax.swing.JInternalFrame
Has no border or menu bar.javax.swing.JWindow
Outermost container of Swing applets. javax.swing.JApplet
Used as the outermost container of an application.
javax.swing.JFrame
DescriptionSwing Container
•JInternalFrame is a lightweight container so must be place inside a heavyweight container (JFrame).
17
Copyright© Objective Consulting Intro to Java – GUI 33
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 34
JRootPane and its children
18
Copyright© Objective Consulting Intro to Java – GUI 35
Members of a JRootPaneDescriptionRoot pane member
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.
Glass pane
Implements a menu bar.Menu bar
Contains the children of the top-level container. (e.g. JButton, JTextField)
Content pane
Implements Z-ordering. By default it places all children in the content pane.
Layered pane
Copyright© Objective Consulting Intro to Java – GUI 36
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”);
}
19
Copyright© Objective Consulting Intro to Java – GUI 37
Model-View-Controller• MVC is one of the most well known design patterns.
Let’s 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 38
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 browser’s “controller” updates the view of the document which appears as if we have jumped to that section.
20
Copyright© Objective Consulting Intro to Java – GUI 39
Model-View-Controller• Model: data
• View: 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 40
Model-View-Controller
Model
Controller
View
User interface event
update if content changed (typing in textfield)
visual only update (scrolling)
notifies when content changes
read contents
21
Copyright© Objective Consulting Intro to Java – GUI 41
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.
Model
View
Controller
Copyright© Objective Consulting Intro to Java – GUI 42
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.
22
Copyright© Objective Consulting Intro to Java – GUI 43
UI Delegate
Basic Button UI
Component UI
Button UI
JButton
JComponent
Abstract Button
ui: Component UI
Copyright© Objective Consulting Intro to Java – GUI 44
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)
23
Copyright© Objective Consulting Intro to Java – GUI 45
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 46
Pluggable Look-and-Feel (L&f)• If you don’t set the L&F then the default is the
“Java” look and feel which is metal.
• Let’s 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 isrunning. If the application was running on Windows the L&F would be Windows (image on the right).
24
Copyright© Objective Consulting Intro to Java – GUI 47
Setting System Look-and-Feelpublic 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 48
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);
25
Copyright© Objective Consulting Intro to Java – GUI 49
Changing L&F at run-time• The PLAF even permits changing the L&F at run-
time. 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 50
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.
26
Copyright© Objective Consulting Intro to Java – GUI 51
javax.swing.ButtonModel states
The state in which the user has pressed the mouse down on the button but not released it.
Pressed
The state in which the button has been pressed, but not activated.
Armed
The state in which the button has been activated.Selected
The state in which the mouse if positioned over the button.
Rollover
The state in which the button can be selected or pressed.
Enabled
DescriptionState
Copyright© Objective Consulting Intro to Java – GUI 52
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.
27
Copyright© Objective Consulting Intro to Java – GUI 53
Swing Models – partial list
Defines an ordered list of elements.ListModelAn abstraction of a selection on a list and provide the capability to specify those elements that are selected.
ListSelectionModel
Defines a two-dimensional table of objects.TableModelA generalized document that contains various kinds of text.
Document
Subinterface of ListModel, which adds the capability to specify one of the items as selected.
ComboBoxModel
An abstraction that defines state for various buttons such as check boxes, radio buttons and normal buttons.
ButtonModelDescriptionModel Interface Name
Copyright© Objective Consulting Intro to Java – GUI 54
Swing Models Implementations
AbstractListModelListModelDefaultListSelectionModelListSelectionModelAbstractTableModel DefaultTableModelTableModelAbstractDocument, DefaultStyledDocument, PlainDocument
Document
DefaultButtonModelButtonModelPartial or full implementing classModel Interface Name
28
Copyright© Objective Consulting Intro to Java – GUI 55
Model usage by component
JListListModelJList, JTableListSelectionModelJTableTableModelJTable, JTableHeaderTableColumnModelJTextField, JTextArea, JPasswordField, JTextPane
Document
JComboBoxComboBoxModel
AbstractButton, JMenu, ButtonGroup
ButtonModelUsed by these componentsModel Name
Copyright© Objective Consulting Intro to Java – GUI 56
ButtonModel• From the previous tables we can see that
– the abstraction defined by the button model interface relates tothe 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.
29
Copyright© Objective Consulting Intro to Java – GUI 57
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 58
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.
30
Copyright© Objective Consulting Intro to Java – GUI 59
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 60
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 JListmore closely.
31
Copyright© Objective Consulting Intro to Java – GUI 61
Some Components• JScrollPane
• JTextArea
• JList
Copyright© Objective Consulting Intro to Java – GUI 62
JScrollPane• Purpose
• Basic Usage
• JTextArea examples– Problems & solutions
• Scroll bars– Basics
– Problems & solutions
32
Copyright© Objective Consulting Intro to Java – GUI 63
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 64
JScrollPane – Basic Usage• Add the component to be scrolled to the JScrollPane.
• Add the JScrollPane to the container.
textArea = new JTextArea(3, 20); // 3 rows,20 cols
….
// 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);
33
Copyright© Objective Consulting Intro to Java – GUI 65
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 66
JScrollPane – JTextArea ExampleJTextArea 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 injavaman.SwingEx8 found in the Intro source code.
34
Copyright© Objective Consulting Intro to Java – GUI 67
JScrollPane – JTextArea ExampleJTextArea 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 injavaman.MessagePanel found in the Intro source code.
Copyright© Objective Consulting Intro to Java – GUI 68
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_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED is default
35
Copyright© Objective Consulting Intro to Java – GUI 69
JScrollPane – ScrollbarsGetting 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 suchthat 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. “I’m 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 70
JScrollPane – ScrollbarsGetting 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 theJScrollPane(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 Phil’s 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.
36
Copyright© Objective Consulting Intro to Java – GUI 71
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 72
Advanced Swing - JList• Purpose
• Architecture
• Demo 1 – Simple Usage
• Getting Selections
• Selection Modes
• Setting and Changing List Contents
37
Copyright© Objective Consulting Intro to Java – GUI 73
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 74
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.
38
Copyright© Objective Consulting Intro to Java – GUI 75
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 76
JList – Getting the selection(s)• There are a number of methods for getting the selections but the
most commonly used are:Object getSelectedValue()
Returns the first selected value, or null if the selection is empty.Object[] 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());
}
}
39
Copyright© Objective Consulting Intro to Java – GUI 77
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 untilvalueAdjusting is false.
Copyright© Objective Consulting Intro to Java – GUI 78
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());
}
}.
40
Copyright© Objective Consulting Intro to Java – GUI 79
JList - ListSelectionListenerTo 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 80
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.
41
Copyright© Objective Consulting Intro to Java – GUI 81
JList – Selection Modes• Since MULTIPLE_INTERVAL_SELECTION is the default let’s
see how to force SINGLE_SELECTION.
jList1.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// OR use the method from JList that simply delegates jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Copyright© Objective Consulting Intro to Java – GUI 82
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.
42
Copyright© Objective Consulting Intro to Java – GUI 83
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 84
JList – Dynamic List contents• If we have an application in which elements
must be dynamically added or removed we must use a DefaultListModel.
• The JList’s view will update its appearance accordingly when elements are added or removed.
43
Copyright© Objective Consulting Intro to Java – GUI 85
JList – Dynamic List contents• Let’s look at how we can make the right list dynamic.
JList rightList = new JList(new DefaultListModel());
// Handler for the add button
// Find the boundaries of the selection intervals (all intervals)
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 Intro to Java – GUI 86
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.
44
Copyright© Objective Consulting Intro to Java – GUI 87
JList - Summary• SUMMARY
Copyright© Objective Consulting Intro to Java – GUI 88
Putting it all together• A Swing GUI for Remote File Viewer