Java Swing Programming

Werbung
Fachbereich Informatik und Elektrotechnik
Java Swing
Advanced Java
Java Swing
Programming
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Java Swing
Design Goals
The 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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
AWT
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
Widget = Window Gadget
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.)
AWT and Swing are part of the JFC (Java Foundation Classes)
Easy upgrading using "J":
Programming in Java,  Helmut Dispert
Applet
Button
→
→
JApplet
JButton
Fachbereich Informatik und Elektrotechnik
Classes, Packages
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Component
Container
Panel
Applet
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Class JApplet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
Component
Container
Class JApplet:
An extended version of java.applet.Applet
that adds support for the JFC/Swing
component architecture.
Panel
Applet
JApplet
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Classes, Packages
Syntax:
public class Name extends java.applet.Applet
{
...
}
class
imported package
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JFC
Java Foundation Classes
AWT
• AWT:
the original GUI toolkit
Swing
• Swing:
the new GUI toolkit
Accessibility
• Accessibility:
tools to develop support for users challenged
by traditional UI’s
2D API
• 2D API:
classes for more complex use of painting,
shape, colour, and fonts
Drag and Drop
• Drag and Drop:
tools for implementing the transfer of
information between Java applications and
native applications
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JFC
Java Foundation Classes
consist of:
•
•
•
•
•
Abstract Windowing Toolkit (AWT)
Swing
–
Ab JDK1.2
–
Leichtgewichtige Komponenten (ohne Betriebsystem Support)
Die Swing-Klassenbibliothek baut auf AWT auf und erweitert diese
um Komponenten und dem Model-View-Controller (MVC)
Java 2D
–
Erstellen und bearbeiten von Bildern und 2D Grafiken
Drag and Drop
–
Verschieben mit der Maus
Accessibility
–
Schnittstelle zur Einbindung zusätzlicher Ein- und Ausgabegeräte.
continued
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JFC
Java Foundation Classes
consist of:
•
Abstract Windowing Toolkit (AWT)
– Schwergewichtige Komponenten (verwenden betriebsystemnahe
Funktionen)
– Umfasst drei Elemente
• Komponenten
– Oberflächenelemente
– Beispiel: Buttons, Labels, ...
• Container
– Gruppieren und enthalten Oberflächenelemente
– Beispiel: Fenster
• Layout Manager
– Legen fest, wie die Komponenten im Container
angesprochen werden können
– Beispiel: Border Layout (Nord, Süd, Ost, West, Center)
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
AWT
Architecture of the Swing Class Library
OS-independent
part of API
OS-dependent
part of API
Motif
ButtonPeer
Button
ButtonPeer
Windows
ButtonPeer
The button peer interface specifies the methods that all implementations of Abstract
Window Toolkit buttons must define.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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 lookand-feel to a native peer.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
AWT
Architecture of the Swing Class Library
•
•
•
•
Heavyweight Komponenten (AWT)
– Die Anbindung der Komponenten geschieht mit
sogenannten Peer-Objekten, welche für jedes
Betriebsystem neu geschrieben werden.
Lightweight Komponenten (Swing)
– Werden von Java selbst gezeichnet
– Die Containerklassen (Frame, Dialog, Window, Applet)
wurden aus AWT übernommen und erweitert:
JFrame, JDialog, JWindow, JApplet als toplevel Container
Alle leichtgewichtigen Komponenten können direkt in den
Frame gezeichnet werden.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing
Swing - Lightweight Components
Swing uses lightweight components
It uses a variant of the
Model View Controller Architecture (MVC)
It has Pluggable Look And Feel (PLAF)
It uses the Delegation Event Model
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing
Lightweight vs. Heavyweight
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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
Controller
Programming in Java,  Helmut Dispert
Model
View
Fachbereich Informatik und Elektrotechnik
Model View Controller
Model
Model
• •Encapsulates
Encapsulatesapplication
applicationstate
state
• •Responds
to
state
queries
Responds to state queries
• •Exposes
Exposesapplication
applicationfunctionality
functionality
• •Notifies
Notifiesviews
viewsofofchanges
changes
State
Query
State
Change
Change
Notification
View
View
View Selection
• •Renders
Rendersthe
themodels
models
• •Requests
updates
Requests updatesfrom
frommodels
models
• •Sends
user
gestures
to
controller
Sends user gestures to controller
• •Allows
Allowscontroller
controllertotoselect
selectview
view
User Gestures
Method Invocations
Events
Programming in Java,  Helmut Dispert
Controller
Controller
• •Defines
Definesapplication
applicationbehaviour
behaviour
• •Maps
user
actions
to
Maps user actions tomodel
modelupdates
updates
• •Selects
view
for
response
Selects view for response
• •One
Onefor
foreach
eachfunctionality
functionality
Fachbereich Informatik und Elektrotechnik
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
M
UI
Object
UI
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".
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Modified MVC – UI Delegate
Example: JButton
ButtonUI
View
Controller
JButton
Button
Model
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Modified MVC – UI Delegate
Example: JButton - Pluggable Look and Feel(PLAF)
ButtonUI
View
Controller
JButton
Button
Model
Programming in Java,  Helmut Dispert
UIFactory
Fachbereich Informatik und Elektrotechnik
Modified MVC – UI Delegate
Swing Look & Feel
AWT Look & Feel
Component
JComponent
(MVC Model)
MVC
View
MVC
Controller
Peer
(native)
ComponentUI (Delegate)
Platform
Widget
(native)
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing Components and Container
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing Packages
Important Swing Packages:
• javax.accessibility
Provides accessibility for disabled persons
• javax.swing
Provides a set of "lightweight" (all-Java language)
components that, to the maximum degree possible, work
the same on all platforms.
• javax.swing.border
Provides classes and interface for drawing specialized
borders around a Swing component.
• javax.swing.event
Provides for events fired by Swing components.
javax.swing.plaf
Provides user interface objects built according to the
Basic look-and-feel.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
RootPane
Structure of a RootPane
Menu
ContentPane
GlasPane
LayeredPane
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing Components
AbstractButton
Abstract Superclass for Swing buttons.
ButtonGroup
Encapsulates a mutually exclusive set of buttons.
ImageIcon
Encapsulates an icon.
JApplet
The Swing version of Applet.
JFrame
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.
JButton
The Swing push button class.
JCheckBox
The Swing check box class.
JComboBox
Encapsulates a combo box (a combination of a
drop-down list and text field).
JLabel
The Swing version of a Label.
continued
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Swing Components
JOptionPane
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.
JPasswordField
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.
JRadioButton
The Swing version of a radio button.
JScrollPane
Encapsulates a rectangular area in which a
component may be viewed.
JTabbedpane
Encapsulates a tabbed window.
JTable
Encapsulates a table-based control.
JTextField
The Swing version of a text field.
JTree
Encapsulate a tree-based control.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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)
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Sample Program - PLAF
Windows
Look-and-Feel
Motif
Look-and-Feel
Metal
Look-and-Feel
Java
SwingExamp01
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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);
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Sample Program - PLAF
public SwingExamp01()
{
super("Our first Swing-Program");
//Panel zur Namenseingabe hinzufügen
JPanel 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ügen
JList list = new JList(MONTHS);
list.setToolTipText("Select the month of your birthday");
getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
//Panel mit den Buttons hinzufügen
JPanel buttonPanel = new JPanel();
JButton button1 = new JButton("Metal");
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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-Listener
addWindowListener(new WindowClosingAdapter(true));
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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";
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Sample Program - PLAF
}
}
}
}
//LAF umschalten
UIManager.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());
}
}
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers
Layout Managers
are used to arrange components according to
predefined patterns and to allow more complex
UIs.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers
Mit einem Layout-Manager werden die Komponenten nach
bestimmten Vorgaben auf einer Bedienoberfläche bzw. in einem
Container angeordnet.
– Jeder Container hat eine standardmässige Referenz auf
ein Objekt, das ein Interface LayoutManager
implementiert.
– Mit setLayout(LayoutManager) kann dieser
überschrieben werden.
– Komponenten werden mit add(Component) dem
Container hinzugefügt und in dieser Reihenfolge
angeordnet.
– Bei Top-Level Containern muss der Aufruf der beiden
Methoden auf der ContentPane erfolgen.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers - Flow Layout
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ügen
setLayout(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();
}
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers - Grid Layout
import java.awt.*;
import java.awt.event.*;
public class Grid
extends 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ügen
setLayout(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();
}
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers - Grid Bag Layout
Example:
GridLayout
Java
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers - Grid Bag Layout
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Layout Managers
Further Layout Manager
• CardLayout
• Kann mehrere Container in einem übergeordneten Container
anordnen, erzeugt einen Stapel von Containern, die
hintereinander liegen.
• BoxLayout
• Ähnlich wie FlowLayout. Die zu einem Container hinzugefügten
Komponenten werden von oben nach unten oder von links
nach rechts angeordnet.
• OverlayLayout
• Ermöglicht das Stapeln von Komponenten bzw. das
Übereinanderlegen.
• ViewportLayout
• Ein Viewport ist ein sichtbarer Bereich eines scrollbaren
Fensters.
• NullLayout
• Komponenten können durch Vorgabe fester Koordinaten
platziert werden (absolute Positionierung).
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
NullLayout
import java.awt.*;
import java.awt.event.*;
public class NullLayout
extends 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ügen
setSize(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);
}
}
}
Programming in Java,  Helmut Dispert
Java
Fachbereich Informatik und Elektrotechnik
Swing MVC
Advanced Java
MVC Example
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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);
}
}
Java
Programming in Java,  Helmut Dispert
Create
model, view, and controller
Herunterladen