Upload
lynhi
View
227
Download
0
Embed Size (px)
Citation preview
China Jiliang University
Java Web Applications, Helmut Dispert
Java
Programming in Java
Java Swing Programming
China Jiliang University
Java Web Applications, Helmut Dispert
Java Swing
Design GoalsThe overall goal for the Swing project was:To build a set of extensible GUI components to enable developers to more rapidly develop powerful Java front ends for commercial applications.
The design goals mandated that Swing would:1. Be implemented entirely in Java to promote cross-platform consistency and
easier maintenance.2. Provide a single API capable of supporting multiple look-and-feels so that
developers and end-users would not be locked into a single look-and-feel.Enable the power of model-driven programming without requiring it in the highest-level API.
3. Adhere to JavaBeans design principles to ensure that components behave well in IDEs and builder tools.
4. Provide compatibility with AWT APIs where there is overlapping, to leverage the AWT knowledge base and ease porting.
Ref.:Sun Microsystems
China Jiliang University
Java Web Applications, Helmut Dispert
Contents
Ø Introduction§ History
§ JFC – Java Foundation Classes
Ø What makes Swing so special?§ Lightweight Components
§ PLAF
§ MVC
§ Delegation Event Model
Ø How to use Swing§ Components
§ JComponent
§ Layouts
§ Example
Ø Summary
China Jiliang University
Java Web Applications, Helmut Dispert
AWT
Widget = Window Gadget
Problems with the AWT
• AWT is not functional enough for full scale applications– small widget library– widgets have only basic functionality– extensions commonly needed
• AWT Components rely on native peers– no platform independency:
widgets do not perform exactly the same on different platforms
China Jiliang University
Java Web Applications, Helmut Dispert
AWT vs. Swing APIs
Java AWT (Abstract Windowing Toolkit)
Ø Package: java.awtØ GUI functionality (graphical user interface)Ø Component libraries:
labels, buttons, textfields, etc. (platform dependent)Ø Helper classes:
event handling, layout managers (window layouts), etc.
The Swing APIs
Ø Package: javax.swingØ Greater platform independence
- portable "look and feel" (buttons, etc.)
Easy upgrading using "J": Applet → JAppletButton → JButton
AWT and Swing are part of the JFC (Java Foundation Classes)
China Jiliang University
Java Web Applications, Helmut Dispert
Classes, Packages
Component
Container
Panel
Applet
java.lang.Objectjava.awt.Component
java.awt.Containerjava.awt.Panel
java.applet.Applet
China Jiliang University
Java Web Applications, Helmut Dispert
Class JApplet
Component
Container
Panel
Applet
java.lang.Objectjava.awt.Component
java.awt.Containerjava.awt.Panel
java.applet.Appletjavax.swing.JApplet
JApplet
Class JApplet:An extended version of java.applet.Applet that adds support for the JFC/Swingcomponent architecture.
China Jiliang University
Java Web Applications, Helmut Dispert
Classes, Packages
public class Name extends java.applet.Applet{
...}
Syntax:
imported package
class
China Jiliang University
Java Web Applications, Helmut Dispert
JFC
• AWT:the original GUI toolkit
• Swing:the new GUI toolkit
• Accessibility:tools to develop support for users challenged by traditional UI’s
• 2D API:classes for more complex use of painting, shape, colour, and fonts
• Drag and Drop:tools for implementing the transfer of information between Java applications and native applications
Java Foundation Classes
AWT
Swing
Accessibility
2D API
Drag and Drop
China Jiliang University
Java Web Applications, Helmut Dispert
JFC
Java Foundation Classesconsist of:
• Abstract Windowing Toolkit (AWT)
• Swing
– Since JDK1.2
– Lightweight Components (without OS support)The Swing Class library based on AWT, expansion with components and the Model-View-Controller (MVC)
• Java 2D
– Image Design, 2D Graphics, GUI Design (Graphical User Interfaces)
• Drag and Drop
– Drag and Drop with mouse control
• Accessibility
– Interface to include additional I/O-devices.
continued
China Jiliang University
Java Web Applications, Helmut Dispert
JFC
Java Foundation Classesconsist of:
• Abstract Windowing Toolkit (AWT)
– Heavyweight Components (using OS-based function)
– Includes three elements
• Components
– UI elements
– Example: Buttons, Labels, ...
• Container
– Grouping of UI elements
– Example: Window
• Layout Manager
– Decide how components will be organized and accessed in the container
– Example: Border Layout (Nord, Süd, Ost, West, Center)
China Jiliang University
Java Web Applications, Helmut Dispert
AWT
Architecture of the Swing Class Library
OS-independentpart of API
OS-dependentpart of API
Button
WindowsButtonPeer
MotifButtonPeer
ButtonPeer
The button peer interface specifies the methods that all implementations of Abstract Window Toolkit buttons must define.
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components
Concept of Java peers:When instantiating an AWT component the native environment creates the component. User sees the native look-and-feel, component acts like the native control.Peer: native code that provides this look-and-feel.Each platform has its own set of peers.
Example:A Java button appears (and acts) as a Windows button under Windows, as a Macintosh button under Macintosh, and as a Unix button under Unix.
Problem:Not all native controls respond in the same way to the same events, so that a Java program shows different behavior under different Java AWT environments.
Solution:Lightweight components, written entirely in Java. Swing provides a set of pure Java lightweight components, ensuring better cross-platform compatibility.A lightweight component subclasses java.awt.Component - implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer.
China Jiliang University
Java Web Applications, Helmut Dispert
AWT
• Heavyweight Komponenten (AWT)
– Interface of the components with so-called peer-objects, that have to be rewritten for each operationg system (OS)
• Lightweight Komponenten (Swing)
– Directly programmed in Java
– Container Classes (Frame, Dialog, Window, Applet) come from AWT and were expanded:
• JFrame, JDialog, JWindow, JApplet as toplevel Container
• All lightweight components can directly be drawn in the Frame.
Architecture of the Swing Class Library
China Jiliang University
Java Web Applications, Helmut Dispert
AWT
AWT - Heavyweight Components
Ø RectangularØ OpaqueØ Always drawn over top of lightweight componentsØ Rely on native peers
§ Look and Feel tied to operating system § functionality determined by operating system§ faster, because the OS handles the work
China Jiliang University
Java Web Applications, Helmut Dispert
Swing
Swing - Lightweight Components
Ø Swing uses lightweight components
Ø It uses a variant of theModel View Controller Architecture (MVC)
Ø It has Pluggable Look And Feel (PLAF)
Ø It uses the Delegation Event Model
China Jiliang University
Java Web Applications, Helmut Dispert
Swing
Swing - Lightweight Components
Ø Any shapeØ Transparent portionsØ OverlapØ Mouse events fall through transparent portionsØ Do not rely on native peers
§ Look and Feel drawn at runtime so can vary§ functionality is the same on all platforms§ slower because Java has to do the work
China Jiliang University
Java Web Applications, Helmut Dispert
Swing
Lightweight vs. Heavyweight
China Jiliang University
Java Web Applications, Helmut Dispert
Model View Controller
Roots in MVC
Swing architecture is rooted in the model-view-controller(MVC) design that dates back to SmallTalk.
MVC architecture calls for a visual application to be broken up into three separate parts:
Ø A model that represents the data for the application.
Ø The view that is the visual representation of that data.
Ø A controller that takes user input on the view and translates that to changes in the model.
China Jiliang University
Java Web Applications, Helmut Dispert
Model View Controller
Independent MVC-elements:
Ø Model § state data for each component§ different data for different models
Ø View § how the component looks onscreen,
displays the dataØ Controller
§ dictates how the component reacts to I/O events
ControllerModel View
China Jiliang University
Java Web Applications, Helmut Dispert
Model View Controller
Model
• Encapsulates application state• Responds to state queries• Exposes application functionality• Notifies views of changes
Model
• Encapsulates application state• Responds to state queries• Exposes application functionality• Notifies views of changes
Controller
• Defines application behaviour• Maps user actions to model updates• Selects view for response• One for each functionality
Controller
• Defines application behaviour• Maps user actions to model updates• Selects view for response• One for each functionality
View
• Renders the models• Requests updates from models• Sends user gestures to controller• Allows controller to select view
View
• Renders the models• Requests updates from models• Sends user gestures to controller• Allows controller to select view
StateQuery
ChangeNotification
StateChange
View Selection
User Gestures
Method Invocations
Events
China Jiliang University
Java Web Applications, Helmut Dispert
Modified MVC – UI Delegate
The Java Swing Architecture uses a modified MVC-model in which the "view" and "controller" are combined in a so-called UI object (User-interface).
Component
UIObject
MUI
Manager
The UI Object is also called the "UI delegate" or the "delegate object".The modified MVC-model is also referred to a "separable model architecture".
China Jiliang University
Java Web Applications, Helmut Dispert
Modified MVC – UI Delegate
Example: JButton
ButtonUI
ButtonModel
Controller View
JButton
China Jiliang University
Java Web Applications, Helmut Dispert
ButtonUI
Modified MVC – UI Delegate
ButtonModel
Controller View
JButton
Example: JButton - Pluggable Look and Feel(PLAF)
UIFactory
China Jiliang University
Java Web Applications, Helmut Dispert
ComponentUI (Delegate)
Modified MVC – UI Delegate
JComponent(MVC Model)
MVCController
MVCView
Swing Look & Feel
Component
PlatformWidget(native)
Peer(native)
AWT Look & Feel
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components and Container
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Packages
Important Swing Packages:
• javax.accessibilityProvides accessibility for disabled persons
• javax.swingProvides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
• javax.swing.borderProvides classes and interface for drawing specialized borders around a Swing component.
• javax.swing.eventProvides for events fired by Swing components. javax.swing.plafProvides user interface objects built according to the Basic look-and-feel.
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components: JComponent, JFrame
Swing components are similar to components in the Abstract Windowing Toolkit (AWT) but are subclasses of the JComponent class.
§ common root of most of the Swing GUI classes§ guiding framework for GUI objects§ extends java.awt.Container class
Swing applications are subclasses of the class JFrame.
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components
Swing components and containers are added to a content pane which represents the full frame area.The content pane is added to the frame.
China Jiliang University
Java Web Applications, Helmut Dispert
RootPane
Structure of a RootPane
GlasPane
Menu
ContentPane
LayeredPane
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components
The Swing version of a Label.JLabel
Encapsulates a combo box (a combination of a drop-down list and text field).
JComboBox
The Swing check box class.JCheckBox
The Swing push button class.JButton
The Swing frame that is more sophisticated than the AWT frame. We can add components in layers, add a menu bar, or paint over the component through a component called a glass pane.
JFrame
The Swing version of Applet.JApplet
Encapsulates an icon.ImageIcon
Encapsulates a mutually exclusive set of buttons.ButtonGroup
Abstract Superclass for Swing buttons.AbstractButton
continued
China Jiliang University
Java Web Applications, Helmut Dispert
Swing Components
The Swing version of a radio button. JRadioButton
Encapsulates a rectangular area in which a component may be viewed.
JScrollPane
Encapsulates a tabbed window. JTabbedpane
Encapsulates a table-based control. JTable
The Swing version of a text field. JTextField
Encapsulate a tree-based control. JTree
A text field that does not display the text entered into it, but displays the specified character, e.g. * as input is given into the field.
JPasswordField
The option panes in Swing. Option panes are dialog boxes that display some information to the user or get confirmation from the user so that the program can be executed further based on the choice the user makes.
JOptionPane
China Jiliang University
Java Web Applications, Helmut Dispert
Look and Feel
PLAF - Pluggable Look and Feel
Swing supplies three choices for look and feel:
- Metal style - Swing's default cross-platform LAF
- Motif X-Windows system style LAF
- Windows style LAF
- Mac style (not part of the JDK)
- New styles can be designed
- Style can be reset/changed at runtime
Method:setLookAndFeel(plaf)
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
WindowsLook-and-Feel
MotifLook-and-Feel
MetalLook-and-Feel
SwingExamp01
Java
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
import java.awt.event.*;import java.awt.*;import javax.swing.*;
public class SwingExamp01 extends Jframe implements ActionListener{
private static final String[] MONTHS = {"January", "February", "March", "April","May", "June", "July", "August","September", "October", "November", "December"
};
public static void main(String[] args){
SwingExamp01 frame = new SwingExamp01();frame.setLocation(100, 100);frame.pack();frame.setVisible(true);
}
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
public SwingExamp01(){
super("Our first Swing-Program");//Panel zur Namenseingabe hinzufügenJPanel namePanel = new JPanel();JLabel label = new JLabel(
"Name:",new ImageIcon("triblue.gif"), SwingConstants.LEFT
);namePanel.add(label);JTextField tf = new JTextField(30);tf.setToolTipText("Enter your name");namePanel.add(tf);namePanel.setBorder(BorderFactory.createEtchedBorder()); getContentPane().add(namePanel, BorderLayout.NORTH); //Monatsliste hinzufügenJList list = new JList(MONTHS);list.setToolTipText("Select the month of your birthday");getContentPane().add(new JScrollPane(list), BorderLayout.CENTER); //Panel mit den Buttons hinzufügenJPanel buttonPanel = new JPanel();JButton button1 = new JButton("Metal");
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
button1.addActionListener(this);button1.setToolTipText("Metal-Look-and-Feel");buttonPanel.add(button1);JButton button2 = new JButton("Motif");button2.addActionListener(this);button2.setToolTipText("Motif-Look-and-Feel");buttonPanel.add(button2);JButton button3 = new JButton("Windows");button3.addActionListener(this);button3.setToolTipText("Windows-Look-and-Feel");buttonPanel.add(button3);buttonPanel.setBorder(BorderFactory.createEtchedBorder()); getContentPane().add(buttonPanel, BorderLayout.SOUTH);//Windows-ListeneraddWindowListener(new WindowClosingAdapter(true));
}
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
public void actionPerformed(ActionEvent event){
String cmd = event.getActionCommand();try {
//PLAF-Klasse auswählen String plaf = "unknown";if (cmd.equals("Metal")) {plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (cmd.equals("Motif")) {plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
} else if (cmd.equals("Windows")) {plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
}
China Jiliang University
Java Web Applications, Helmut Dispert
Sample Program - PLAF
//LAF umschaltenUIManager.setLookAndFeel(plaf);SwingUtilities.updateComponentTreeUI(this);
} catch (UnsupportedLookAndFeelException e) {System.err.println(e.toString());
} catch (ClassNotFoundException e) {System.err.println(e.toString());
} catch (InstantiationException e) {System.err.println(e.toString());
} catch (IllegalAccessException e) {System.err.println(e.toString());
}}
}
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers
Layout Managers
are used to arrange components according to predefined patterns and to allow more complex UIs.
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers
Layout-Manager are used to render a UI: position and organize components (UI, container).
– Each container has a reference to an object that implements the interface LayoutManager.
– It can be overwritten with setLayout(LayoutManager.
– Components can be added to the container withadd(Component) and are ordered in accordingly.
– When top-level containerare used both methods have to called on the ContentPane.
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Flow Layout
The Flow LayoutØ arranges components in a left-to-right flow, much like lines of text in
a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered.
China Jiliang University
Java Web Applications, Helmut Dispert
import java.awt.*;import java.awt.event.*;
public class Flow extends Frame{public static void main(String[] args){
Flow wnd = new Flow();wnd.setVisible(true);
}
public Flow(){
super("Test FlowLayout");addWindowListener(new WindowClosingAdapter(true));//Layout setzen und Komponenten hinzufügensetLayout(new FlowLayout(FlowLayout.LEFT,20,20));add(new Button("Button 1"));add(new Button("Button 2"));add(new Button("Button 3"));add(new Button("Button 4"));add(new Button("Button 5"));pack();
}}
Layout Managers - Flow Layout
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Border Layout
The BorderLayoutØ lays out a container, arranging and resizing its components to fit in
five regions:north, south, east, west, and center.Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER.
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Grid Layout
The GridLayoutØ lays out a container's components in a rectangular grid. The
container is divided into equal-sized rectangles, and one component is placed in each rectangle.
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Grid Layoutimport java.awt.*;import java.awt.event.*;
public class Gridextends Frame{public static void main(String[] args){
Grid wnd = new Grid();wnd.setVisible(true);
}
public Grid(){
super("Test GridLayout");addWindowListener(new WindowClosingAdapter(true));//Layout setzen und Komponenten hinzufügensetLayout(new GridLayout(4,2));add(new Button("Button 1"));add(new Button("Button 2"));add(new Button("Button 3"));add(new Button("Button 4"));add(new Button("Button 5"));add(new Button("Button 6"));add(new Button("Button 7"));pack();
}}
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Grid Bag Layout
Example:GridLayout
Java
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Grid Bag Layout
The GridBagLayoutØ The GridBagLayout class is a flexible layout manager that aligns
components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area.
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers - Grid Bag Layout
China Jiliang University
Java Web Applications, Helmut Dispert
Layout Managers
Further Layout Manager• CardLayout
• Can order several containers in a higher container, produces a stack of containers that are organized on top of each other.
• BoxLayout
• Similar to the FlowLayout. The components that are added to a container are ordered from top to bottom or from left to right.
• OverlayLayout
• Allows to stack components (overlaying them).
• ViewportLayout
• A viewport is a visible area of a scollable window.
• NullLayout
• Components can be positioned using predefined coordinates (absolute positioning).
China Jiliang University
Java Web Applications, Helmut Dispert
NullLayoutimport java.awt.*;import java.awt.event.*;
public class NullLayoutextends Frame{public static void main(String[] args){NullLayout wnd = new NullLayout();wnd.setVisible(true);
}
public NullLayout(){super("Dialogelemente ohne Layoutmanager");addWindowListener(new WindowClosingAdapter(true));//Layout setzen und Komponenten hinzufügensetSize(300,250);setLayout(null);for (int i = 0; i < 5; ++i) {Button button = new Button("Button"+(i+1));button.setBounds(10+i*35,40+i*35,100,30);add(button);
}}
}
Java
China Jiliang University
Java Web Applications, Helmut Dispert
Swing MVC
Advanced Java
MVC Example
China Jiliang University
Java Web Applications, Helmut Dispert
Swing MVC
Example: Simple Calculator
Main program:The main program initializes everything and ties everything together.
View:creates the display, calls the model as necessary to get information.
Controller:Responds to user requests. It is implemented as an Observer pattern -- the Controller registers listeners that are called when the View detects a user interaction. Based on the user request, the Controller calls methods in the View and Model to accomplish the requested action.
Model:independent of the user interface, performs the basic calculator function.
China Jiliang University
Java Web Applications, Helmut Dispert
Swing MVC
Main program:
import javax.swing.*;
public class CalcMVC {public static void main(String[] args) {
CalcModel model = new CalcModel();CalcView view = new CalcView(model);CalcController controller = new CalcController(model, view);
view.setVisible(true);}
}
Createmodel, view, and controllerJava