ppt - Drexel University

Download Report

Transcript ppt - Drexel University

Introduction to JFC Swing
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
1
Java and user interfaces


Platform independence for user interfaces
has been notoriously hard
Java’s first foray:
AWT (Abstract Window Toolkit)
– provided common code for widgets —
components such as windows, buttons, menus, …
– good first start, but platform independence
wasn’t quite there
• AWT relied on windowing code on native machine
– so in practice, somewhat flaky
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
2
Java and user interfaces (2)


Current Java 2: integrated JFC & Swing
Swing
– GUI component toolkit, including all widgets
– no native windowing code, to improve on AWT

JFC (Java Foundation Classes)
– includes Swing components
– includes other software such as…
• “pluggable look and feel”
• accessibility support for disabled

AWT still there, but we can mostly ignore it
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
3
Building a Swing GUI

Consider the following “SwingApplication”
(courtesy of Sun’s Java Swing Tutorial)

Every app defines a hierarchy of components
– “component” = “widget”
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
4
Model-View-Controller Architecture


What defines a component?
In Swing (and similar frameworks), a
component has three crucial elements:
– Model: what data is associated with component
– View: how the component is displayed on-screen
– Controller: how the component responds to user
interaction / events

Example: the scrollbar
Model
min = 0
max = 255
value = 87
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
View
Controller
mouse click on end
mouse click on bar
mouse drag on scroller
5
Pluggable Look and Feel
Each picture shows the same program but with a
different look and feel
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
6
Swing components

Top-level containers
JFrame
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
JDialog
JApplet
7
Swing components

General-purpose containers
JSplitPane
JScrollPane
JTabbedPane
JToolbar
JPanel
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
8
Swing components

Special-purpose containers
JLayeredPane
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
JInternalFrame
9
Swing components

Basic Controls
JButton
JMenu
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
JComboBox
JSlider
JList
JTextField
10
Swing components

Uneditable displays
JProgressBar
JLabel
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
JToolTip
11
Swing components

Editable displays
JColorChooser
JTable
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
JFileChooser
JText
JTree
12
Creating components

Just call the constructors!
frame = new JFrame (...);
button = new JButton (...);
label = new JLabel (...);
pane = new JPanel ();
…


All we’ve done is create the data structures
Still need to:
– add components to container
– lay out container
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
13
Adding components

Add components to top-level container...
typically, to content pane
frame.getContentPane().add (button);

Add components to intermediate containers
JPanel panel = new Jpanel ();
panel.add (button); // … and more…
frame.getContentPane().add (panel);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
14
Example
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("HelloWorldSwing");
final JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
pack() causes a window to be
sized to fit the preferred size and
layouts of its sub-components
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
15
Laying out components

We could just specify absolute positioning —
i.e., exact window coordinates

Why is this not (typically) a good idea?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
16
Laying out components

Problems with absolute positioning
– window expanded, components stay put
courtesy of
java.sun.com’s
Layout Management
short course
7
3
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
17
Laying out components

Problems with absolute positioning (cont.)
– components designed for a specific
look-and-feel or font size
– components designed for a specific language
Auf Wiedersehen
(note: Wieder = “again”!)
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
18
Laying out components

Solution: Layout managers!
– layout manager = algorithm for positioning and
sizing of GUI components

Swing’s LayoutManager interface
– each Component has:
public Dimension getPreferredSize();
public Dimension getMinimumSize();
public Dimension getMaximumSize();
// desired size
// smallest desired size
// largest desired size
– managers use this info to compute layouts
– caveat: “Layout managers can respect or ignore as much
or as little of this information as they see fit” (!)
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
19
Layout managers

BorderLayout (the default)
JPanel pane = new JPanel();
pane.setLayout (new BorderLayout()); // not really needed
…
pane.add (buttonNorth, BorderLayout.NORTH);
pane.add (buttonCenter, BorderLayout.CENTER);
…
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
20
Layout managers

BorderLayout (cont.)
– can’t add twice in the same place
contentPane.add (buttonNorth1, BorderLayout.NORTH);
contentPane.add (buttonNorth2, BorderLayout.NORTH);
// this second add() puts the second button on top of the first!
– can add spacing with the constructor
JPanel pane = new JPanel();
pane.setLayout (new BorderLayout (5, 20)); // xGap, yGap
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
21
Layout managers

BoxLayout: across or up/down
private void addAButton(String text, Container container) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(button);
}
public BoxWindow() {
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,
BoxLayout.Y_AXIS));
addAButton("Button 1", contentPane);
addAButton("2", contentPane);
addAButton("Button 3", contentPane);
addAButton("Long-Named Button 4", contentPane);
addAButton("Button 5", contentPane);
…
}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
22
Layout managers

GridLayout: equal-sized grid of panels
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(0,2));
// grid layout with 2 columns; doesn’t specify number of rows!
contentPane.add(new
contentPane.add(new
contentPane.add(new
contentPane.add(new
contentPane.add(new
JButton("Button 1"));
JButton("2"));
JButton("Button 3"));
JButton("Long-Named Button 4"));
JButton("Button 5"));
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
23
Layout managers

FlowLayout: flows the rows, you knows
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new
contentPane.add(new
contentPane.add(new
contentPane.add(new
contentPane.add(new
JButton("Button 1"));
JButton("2"));
JButton("Button 3"));
JButton("Long-Named Button 4"));
JButton("Button 5"));
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
24
Layout extras

Spacing components out
– create space with rigid boxes
pane.add (Box.createRigidArea (new Dimension (0,5)));
– create space with “glue” (really bad name!)
container.add (firstComponent);
container.add (Box.createHorizontalGlue());
container.add (secondComponent);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
25
Layout extras

Absolute positioning
Container contentPane = getContentPane();
contentPane.setLayout(null);
b1 = new JButton("one");
contentPane.add(b1);
b2 = new JButton("two");
contentPane.add(b2);
b3 = new JButton("three");
contentPane.add(b3);
Insets insets = contentPane.getInsets();
b1.setBounds(25 + insets.left, 5 + insets.top, 75, 20);
b2.setBounds(55 + insets.left, 35 + insets.top, 75, 20);
b3.setBounds(150 + insets.left, 15 + insets.top, 75, 30);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
26
Borders


Every JComponent can have one or more borders.
The class BorderFactory may be used to create
standard borders
pane.setBorder(BorderFactory.
createLineBorder(Color.black));

Using a compound border, you can combine any two
borders, which can themselves be compound
borders
BorderFactory.createCompoundBorder(border1, border2);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
27
Simple Borders
1
1. Simple Borders
2. Titled Borders
3. Compound Borders
2
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
3
28
Example: SwingApplication

High-level view
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingApplication {
public Component createComponents()
{…}
public static void main (String[] args)
{…}
}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
29
Example: SwingApplication

main()
public Component createComponents()
{…}
public static void main (String[] args) {
…
JFrame frame = new JFrame("SwingApplication");
SwingApplication app = new SwingApplication();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
…
frame.pack();
frame.setVisible(true);
}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
30
Example: SwingApplication

createComponents()
public Component createComponents() {
final JLabel label = new JLabel(labelPrefix + "0
");
JButton button = new JButton("I'm a Swing button!");
… << set actions for button >>
label.setLabelFor(button);
JPanel pane = new JPanel();
pane.setBorder (BorderFactory.createEmptyBorder(30,30,10,30));
pane.setLayout(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
create border space!
return pane;
}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
31
Class exercise: MyLayout

How would we use the layout managers to
produce the following layout?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
32
Example: MyLayout2

How about this layout?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
33
Example: MyLayout2

One possible structure...
BorderLayout ()
West
Center
GridLayout (0,3,10,10)
1
2
3
4
5
6
7
8
3
East
BorderLayout ()
BoxLayout (Y_AXIS)
North
Nina
Up
Pinta
Center
FlowLayout ()
Go
with
the
(vertical glue)
Santa Maria
flow
South
Down
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
34
Handling GUI events




Ok, you’ve laid out the perfect window.
Now the user does something —
an event occurs.
How do you handle the event?
Wait, what events are we talking about?
User clicks a button, presses
Return while typing in a text field,
or chooses a menu item
User moves the mouse over a
component
User closes a frame (main window)
Component gets the keyboard
focus
User presses a mouse button while
the cursor is over a component
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
Component becomes visible
Table or list selection changes
35
Programming the GUI

Sequential/procedural programming
– your program is (almost) always in control
yourFoo()
yourFoo()
yourSubFoo()
systemFoo()
yourSubFoo()
– for user input, the program dictates when/how,
and the user responds
> ls */*.java_
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
36
Programming the GUI

Sequential/procedural programming (cont.)
– the good points
• easy to think about: one event,
then the next, …
• easy to design and represent
with well-known models
• easy to program with today’s
programming languages
– the big bad point
Great for the
programmer…
What about
the user?!?!?
• program dictates when/how
user must respond
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
37
Programming the GUI

Event-driven programming
– system / toolkit handles much of processing
– events on a queue, handled in turn
yourClickHandler()
MAIN
LOOP
yourScrollHandler()
yourKeyHandler()
– advantages
...
• flexible interaction — user decides when/how
• easier coding — you code only the “important” stuff
• better for the programmer and the user!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
38
Ways to handle events

“Macintosh-style” event handling
– decide what the event is
– figure out what window it goes to
– handle the event
void handleEvent (event)
{
switch (event->type)
{
case MOUSE_CLICK:
window = event->window;
<< deal with click >>
case …:
}
}
NB: Pseudocode!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
39
Ways to handle events

Callback model
– create widget, register callback function
– callback function called for each event
void myButtonClickCallback (window, other_data)
{…}
void main ()
{
button = new Button (label, …);
registerCallback (button, CLICK_CALLBACK,
&(myButtonClickCallback));
}
NB: Pseudocode!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
40
Ways to handle events

Object-oriented event handling
– the way Java does it!
– based on the OOP component hierarchy
• define event-handling methods for components
• components can (of course) inherit these methods
from parent components
– also based on the Model-View-Control
Architecture (remember?)
– now let’s look at this in detail…
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
41
Swing sources and listeners


Event sources generate events
Event listeners respond to them
User clicks a button, presses Return while
typing in a text field, or chooses a menu item
ActionListener
User closes a frame (main window)
WindowListener
User presses a mouse button while the cursor
is over a component
MouseListener
User moves the mouse over a component
MouseMotionListener
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
42
ActionEvent

A class with three methods:
String getActionCommand ();
int getModifiers ();
String paramString ();

We won’t use these methods at the moment,
but the keep the class in mind!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
43
ActionListener

An interface with a single method:
public interface ActionListener {
void actionPerformed (ActionEvent e);
}

We implement the interface as follows:
public class MyClassThatListens … implements ActionListener {
…
public void actionPerformed (ActionEvent e) { … }
…
}

Review: How is an interface different from a class?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
44
The 3-step program to handling events

1. Code that implements the listener class
public class MyClass implements ActionListener
{…}

2. Code that implements the listener methods
public void actionPerformed (ActionEvent e) { … }

3. Code that registers the listener to a source
component.addActionListener (instanceOfMyClass);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
45
Example: ButtonTest

Beep when the user clicks the button
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest
{
public static class MyActionListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
step 2
{ Toolkit.getDefaultToolkit().beep(); }
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("Program");
JButton button = new JButton ("Click Me");
button.addActionListener (new MyActionListener());
...
}
step 1
step 3
}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.
46
Java
Methods
TM
Maria Litvin
Gary Litvin
An Introduction
to Object-Oriented Programming
Graphics
Copyright © 2002-2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Classroom teachers and workshop instructors may reproduce these slides for face-to-face
teaching purposes.
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:

Learn about paint and repaint methods

Learn about coordinates and colors

Review shape drawing methods

Learn to use fonts and draw graphics text
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
48
Graphics in Java

Java libraries offer two graphics packages:
Graphics and Graphics2D.

Graphics is really not a package but a class
in the java.awt package, which provides
only most basic capabilities.

Graphics2D and related classes in java.awt
support better graphics with color
gradients, line styles, etc.

Here we only deal with Graphics.
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
49
Graphics in Windows

In a windowing environment, a picture must be
be repainted every time we move, reopen or
reshape the window.

The program must have one “central” place or
method where all the drawing happens.

The operating system sends a “message” to the
program to repaint its window when necessary.
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
50
paint and paintComponent

The javax.swing.JFrame class (which represents
application windows) has one method, called
paint, where all the drawing takes place.

In Swing, paint calls paintComponent for each of
the GUI components in the window.

A programmer creates pictures by overriding the
default paintComponent methods (or the paint
method).
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
51
paint and paintComponent (cont’d)

paint takes one argument of the type Graphics:
import java.awt.*;
import javax.swing.*;
public class MyWindow extends JFrame
{
...
public void paint(Graphics g)
{
Defines the graphics
super.paint(g);
“context” (location, size,
...
coordinates, etc.)
}
}
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
52
paint and paintComponent (cont’d)

The same for paintComponent:
import java.awt.*;
import javax.swing.*;
Or another Swing
GUI component
public class MyCanvas extends JPanel
{
...
public void paintComponent(Graphics g)
{
super.paintComponent(g);
...
}
}
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
53
paint and paintComponent (cont’d)

A programmer never calls paint or
paintComponent directly. repaint is called
instead whenever you need to refresh the
picture (e.g. after adding, moving, or changing
some elements):
MyCanvas canvas = new MyCanvas();
...
balloon.move(dx, dy);
repaint();
...
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
repaint takes no
arguments: the
graphics context
is restored and
sent to
paintComponent
automatically
54
Coordinates
x
Origin: the upperleft corner of the
component
Units: pixels
y
y-axis points down, as
in many other graphics
packages
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
55
Coordinates (cont’d)

A GUI component provides getWidth and getHeight
methods that return its respective dimensions.

They can be used to produce scalable graphics.

getWidth, getHeight only work after the component
has been placed (e.g., don’t call them from a
component’s constructor).
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
56
Coordinates (cont’d)

The position of a rectangle, oval, and even an
arc is defined by using its “bounding rectangle,”
described by x, y, width, height:
x, y
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
57
Colors

The color attribute is set by calling g.setColor
and stays in effect until changed again:
g.setColor(Color.blue);
g.draw...
g.draw...
g.setColor(Color.lightGray);
...

You can form a color with any RGB values:
int rVal = 5, gVal = 255, bVal = 40;
Color yourEyes = new Color (rVal, gVal, bVal);
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
58
Colors (cont’d)

javax.swing.JColorChooser let’s you choose a
color in a GUI application:
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
59
Drawing Basic Shapes
g.drawLine (x1, y1, x2, y2);
g.clearRect (x, y, w, h);
g.drawRect (x, y, w, h);
g.fillRect (x, y, w, h);
g.drawRoundRect (x, y, w, h, horzD, vertD);
g.fillRoundRect (x, y, w, h, horzD, vertD);
g.drawOval (x, y, w, h);
g.fillOval (x, y, w, h);
g.drawArc (x, y, w, h, fromDegr, measureDegrs);
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
60
Basic Shapes (cont’d)
g.drawPolygon (xCoords, yCoords, nPoints);
g.fillPolygon (xCoords, yCoords, nPoints);
g.drawPolyline (xCoords, yCoords, nPoints);
abc g.drawString (str, x, y);
x, y

g.drawImage (img, x, y, this);
ImageObserver,
usually this
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
61
Fonts
Font font = new Font (name, style, size);
"Serif"
abc
"SansSerif"
abc "Monospaced"
abc
g.setFont (font);
Copyright
© 2003
byInterfaces.
Maria Litvin,
Litvin,
andUniversity.
Skylight
CS
680: Developing
User
DarioGary
Salvucci,
Drexel
Publishing. All rights reserved.
int (pixels)
Font.PLAIN
Font.BOLD
Font.ITALIC
62