1cs 680: developing user interfaces. dario salvucci, drexel university. introduction to jfc swing
TRANSCRIPT
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 2
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. 3
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. 4
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. 5
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 = 0max = 255value = 87
View Controller
mouse click on endmouse click on bar
mouse drag on scroller
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 6
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. 7
Swing components
Top-level containers
JFrame JDialog JApplet
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 8
Swing components
General-purpose containers
JSplitPane
JToolbar
JScrollPane
JPanel
JTabbedPane
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 9
Swing components
Special-purpose containers
JLayeredPaneJInternalFrame
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 10
Swing components
Basic Controls
JButton JComboBoxJList
JMenu JSlider JTextField
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 11
Swing components
Uneditable displays
JLabel
JProgressBarJToolTip
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 12
Swing components
Editable displays
JColorChooser JFileChooser
JTreeJTextJTable
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 13
Creating components
Just call the constructors!
All we’ve done is create the data structures
Still need to:– add components to container– lay out container
frame = new JFrame (...);button = new JButton (...);label = new JLabel (...);pane = new JPanel ();…
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 14
Adding components
Add components to top-level container... typically, to content pane
Add components to intermediate containers
frame.getContentPane().add (button);
JPanel panel = new Jpanel ();panel.add (button); // … and more…frame.getContentPane().add (panel);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 15
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. 16
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. 17
courtesy ofjava.sun.com’s
Layout Managementshort course
Laying out components
Problems with absolute positioning– window expanded, components stay put
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 18
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. 19
public Dimension getPreferredSize(); // desired sizepublic Dimension getMinimumSize(); // smallest desired sizepublic Dimension getMaximumSize(); // largest desired size
Laying out components
Solution: Layout managers!– layout manager = algorithm for
positioning and sizing of GUI components Swing’s LayoutManager interface
– each Component has:
– 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. 20
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. 21
Layout managers
BorderLayout (cont.)– can’t add twice in the same place
– can add spacing with the constructorJPanel pane = new JPanel();pane.setLayout (new BorderLayout (5, 20)); // xGap, yGap
contentPane.add (buttonNorth1, BorderLayout.NORTH);contentPane.add (buttonNorth2, BorderLayout.NORTH);// this second add() puts the second button on top of the first!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 22
Layout managers
BoxLayout: across or up/downprivate 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. 23
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 JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 24
Layout managers
FlowLayout: flows the rows, you knows
Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 25
Layout extras
Spacing components out– create space with rigid boxes
– create space with “glue” (really bad name!)
pane.add (Box.createRigidArea (new Dimension (0,5)));
container.add (firstComponent);container.add (Box.createHorizontalGlue());container.add (secondComponent);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 26
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. 27
Borders
Every JComponent can have one or more borders.
The class BorderFactory may be used to create standard borderspane.setBorder(BorderFactory.
createLineBorder(Color.black));
Using a compound border, you can combine any two borders, which can themselves be compound bordersBorderFactory.createCompoundBorder(border1, border2);
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 28
Simple Borders
1. Simple Borders
2. Titled Borders
3. Compound Borders
1
2 3
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 29
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. 30
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. 31
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); return pane; }
create border space!
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 32
Class exercise: MyLayout
How would we use the layout managers to produce the following layout?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 33
Example: MyLayout2
How about this layout?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 34
Example: MyLayout2
West Center East
1 2 3
4 5 6
7 8 3
North
Center
Up
Go with the
flow
South
Down
Nina
Pinta
Santa Maria
(vertical glue)
BorderLayout ()
GridLayout (0,3,10,10) BorderLayout ()
FlowLayout ()
BoxLayout (Y_AXIS)
One possible structure...
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 35
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 closes a frame (main window)
User presses a mouse button while the cursor is over a component
User moves the mouse over a component
Component becomes visible
Component gets the keyboard focus
Table or list selection changes
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 36
Programming the GUI
Sequential/procedural programming– your program is (almost) always in
control
– for user input, the program dictates when/how, and the user responds
yourFoo()yourSubFoo()
systemFoo()yourSubFoo()
yourFoo()
> ls */*.java_
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 37
Programming the GUI
Sequential/procedural programming (cont.)– the good points
• easy to think about: one event,then the next, …
• easy to design and representwith well-known models
• easy to program with today’sprogramming languages
– the big bad point• program dictates when/how
user must respond
Great for theprogrammer…
What aboutthe user?!?!?
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 38
Programming the GUI
Event-driven programming– system / toolkit handles much of
processing– events on a queue, handled in turn
– advantages• flexible interaction — user decides when/how• easier coding — you code only the “important”
stuff• better for the programmer and the user!
MAINLOOP
yourClickHandler()
yourScrollHandler()
yourKeyHandler()
...
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 39
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. 40
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. 41
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 methodsfrom 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. 42
Swing sources and listeners
Event sources generate events Event listeners respond to them
User clicks a button, presses Return whileActionListenertyping in a text field, or chooses a menu item
User closes a frame (main window) WindowListener
User presses a mouse button while the cursorMouseListeneris over a component
User moves the mouse over a componentMouseMotionListener
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 43
ActionEvent
A class with three methods:
We won’t use these methods at the moment, but the keep the class in mind!
String getActionCommand ();int getModifiers ();String paramString ();
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 44
ActionListener
An interface with a single method:
We implement the interface as follows:
Review: How is an interface different from a class?
public interface ActionListener { void actionPerformed (ActionEvent e);}
public class MyClassThatListens … implements ActionListener { … public void actionPerformed (ActionEvent e) { … } …}
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 45
The 3-step program to handling events 1. Code that implements the listener
class
2. Code that implements the listener methods
3. Code that registers the listener to a source
public class MyClass implements ActionListener{ … }
component.addActionListener (instanceOfMyClass);
public void actionPerformed (ActionEvent e) { … }
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 46
Example: ButtonTest
Beep when the user clicks the buttonimport javax.swing.*;import java.awt.*;import java.awt.event.*;
public class ButtonTest{ public static class MyActionListener implements ActionListener { public void actionPerformed (ActionEvent e) { 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 2
step 3
Graphics
JavaJavaMethodsMethods
An Introductionto Object-Oriented Programming
Maria Litvin
Gary Litvin
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
TM
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.
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 48
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 49
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 50
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 51
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 52
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) { super.paint(g); ... }}
Defines the graphics “context” (location, size, coordinates, etc.)
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 53
paint and paintComponent (cont’d)
The same for paintComponent:
import java.awt.*;import javax.swing.*;
public class MyCanvas extends JPanel{ ... public void paintComponent(Graphics g) { super.paintComponent(g); ... }}
Or another Swing GUI component
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 54
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(); ...
repaint takes no arguments: the graphics context is restored and sent to paintComponent automatically
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 55
Coordinates
x
y
Origin: the upper-left corner of the component
y-axis points down, as in many other graphics packages
Units: pixels
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 56
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 57
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 58
Colors
The color attribute is set by calling g.setColor and stays in effect until changed again:
You can form a color with any RGB values:
g.setColor(Color.blue); g.draw... g.draw... g.setColor(Color.lightGray); ...
int rVal = 5, gVal = 255, bVal = 40;Color yourEyes = new Color (rVal, gVal, bVal);
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 59
Colors (cont’d)
javax.swing.JColorChooser let’s you choose a color in a GUI application:
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 60
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 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 61
x, y
Basic Shapes (cont’d)
g.drawPolygon (xCoords, yCoords, nPoints);
g.fillPolygon (xCoords, yCoords, nPoints);
g.drawPolyline (xCoords, yCoords, nPoints);
g.drawString (str, x, y);
g.drawImage (img, x, y, this);
abc
ImageObserver, usually this
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. 62
Fonts
Font font = new Font (name, style, size);
g.setFont (font);
abc "Serif" abc "SansSerif" abc "Monospaced"Font.PLAIN
Font.BOLDFont.ITALIC
int (pixels)
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .