Professional Documents
Culture Documents
Java Swing
2.04.2009
Outline
• Introduction to Swing
• Components and Containers
• Anatomy of an Application
• Layouts
• Event Processing
• Swing and Threads
• Model View Controller concept
• Appendix (if we have time)
• Applets
• Java 2D graphics
http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html 2
How to Learn Swing
• Don’t even try.
• Learn framework principles and design styles.
• Use the API reference, and Swing Tutorials to
discover detailed usage of each component.
Java Documentation
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/package-summary.html
SwingSet - examples
http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html
Tutorial
http://java.sun.com/docs/books/tutorial/uiswing/index.html
3
Java Foundation Classes
6
Top-Level Containers
http://java.sun.com/docs/books/tutorial/ui/features/components.html 7
Containers
Notes:
¾ Container objects group components, arranging
them for display with a layout manager.
containers
8
General-Purpose Containers
9
Basic Controls
10
Components
The essential Swing components
AWT
Swing
11
Example 1
import javax.swing.*;
JFrame
Layout Managers
Organizing Layout of components in a container
null FlowLayout GridLayout
none,
Left to right,
programmer
Top to bottom
sets x,y,w,h
s
Combinations
JButtonJButton
JTextArea
Combinations
JButton JButton
JFrame
n JPanel: FlowLayout
JPanel: BorderLayout
c
JTextArea
Code: null layout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);
press me
Code: FlowLayout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
FlowLayout L = new FlowLayout( );
JButton b1 = new JButton(“press me”);
JButton b2 = new JButton(“then me”);
p.setLayout(L);
p.add(b1);
p.add(b2);
f.setContentPane(p); press me then me
http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html
myPane.setLayout(new BoxLayout(myPane, BoxLayout.PAGE_AXIS));
Component.CENTER_ALIGNMENT
Component.RIGHT_ALIGNMENT
Component.LEFT_ALIGNMENT
21
A simple Swing program - Events
Events
• objects communicate by “firing” and “handling”
events
• events are sent from a single source object to one
or more registered listener objects
2
2
Types of Event Listeners
Act that results in event Listener type
User clicks a button, presses Return while typing in a ActionListener
text field, or chooses a menu item
24
Event Handling
class MyListener implements ActionListener {
…
public void actionPerformed( ActionEvent event ) {
// react to event
…
}
}
…
// instantiate event listener
ActionListener listener = new MyListener();
…
// instantiate event source
JButton button = new JButton( “Hello” );
…
// register event listener with event source
button.addActionListener( listener );
25
Example using local class
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
}
);
JDialog
Every dialog is dependent on a frame
A dialog can be modal. When a modal dialog is
visible it blocks user input to all other windows
in the program.
int n = JOptionPane.showOptionDialog(
frame, "You are listening about Swing \n" +
"Do you already think Java?",
"Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
Swing and Threads
Swing components are NOT Thread safe
• The signgle-thread rule
• Once a Swing component has been realized (A
Swing component that’s a top level windows is
realized by having one of these methods invoked
on it: setVisible(), show(), or pack()), all code that
might affect or depend on the state of that
component should be executed in the event-
dispatching thread.
• Exception to the rule: A few operations are
guaranteed to be thread-safe.
29
Safe Swing code
javax.swing.SwingUtilities.invokeLater(
new Runnable(){
public void run(){
// Access to components
}
}
);
31
Handle a job in the background
32
Model/View/Controller
from Krasner and Pope
http://www.itu.dk/courses/VOP/E2005/VOP2005E/8_mvc_krasner_and_pope.pdf
33
Model/View/Controller
MVC roles:
¾ model
complete, self-contained representation of
object managed by the application
e.g., spreadsheet document
provides a number of services to
manipulate the data
e.g., recalculate, save
computation and persistence issues
¾…
try to separate the model and its services
so that it is Swing-free
34
Model/View/Controller
MVC roles:
¾ view
tracks what is needed for a particular perspective
of the data
e.g., bar chart view
presentation issues
¾ controller
gets input from the user, and uses appropriate
information from the view to modify the model
e.g., get slider value, trigger chart modify
interaction issues
Separation:
¾ you can modify or create views without
affecting the underlying model
36
MVC
as seen by Sun
37
Pluggable Look and Feel
• UIManager.setLookAndFeel(
“javax.swing.plaf.metal.MetalLookAndFeel”
);
http://java.sun.com/docs/books/tutorial/ui/overview/demo.html
39
Extra part
• Applets
• Graphics
40
Applets
JApplet is like a JFrame
Already has a panel JApplet
Access panel with JApplet.getContentPane( )
Called by browser:
init( ) - initialization
start( ) - resume processing (e.g. animations)
stop( ) - pause
destroy( ) - cleanup
paint( ) - redraw stuff (‘expose’ event)
Application + Applet
import javax.swing.*;
class helloApp {
Command line Browser
public static void main(String[] args){
JFrame f = new JFrame(“title”);
mainPanel p = new mainPanel();
f.setContentPane(p);
f.show();
}
} JFrame or JApplet
class helloApplet extends JApplet {
public void init(){ contentPane
mainPanel p = new mainPanel();
getContentPane().add(p);
}
}
}
add(b); JButton
}
Applet Security
No read/write on client machine
Can’t execute programs on client machine
Communicate only with server
“Java applet window” Warning
Java 2D API
Graphics
4
5
Graphics
Window is like a painter’s canvas
App must paint its window contents
Java components paint themselves
Anything else: Programmer
When to paint?
How to paint?
JButton
Coordinate System
Upside-down Cartesian
(0,0) (width,0)
JButton
JPanel
Painting in Java
import java.awt.Graphics
import java.awt.Graphics2D // Java2
Graphics g = myJPanel.getGraphics( );
Graphics2D g2 = (Graphics2D) g;
2. Paint in it
g2.drawLine(x1,y1, x2,y2);
Graphics Primitives
http://java.sun.com/docs/books/tutorial/2d/geometry/primitives.html
Draw Fill
Point (x,y)
Line (pt1,pt2)
PolyLine (pt list)
Arc
Oval (pt, w,h)
Rectangle (pt, w,h)
RoundRectangle
Color
Font
Stroke attributes:
¾ Line width, dash, end caps, joins, miter
Paint attributes:
¾ Color, gradient, texture
Composite:
¾ Blending
Transforms:
¾ Translate, rotate, flip, shear, scale
Code
public class MyPanel extends JPanel {
Graphics2D g2 = (Graphics2D)g;
// our drawing:
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
g2.setColor(new Color(0,0,0));
g2.drawString("Hello World", 10, 10);
}
} Hello World
Graphics2D g2 = off_Image.createGraphics();
53
Reading/Loading Image
try {
img = ImageIO.read(new File(“mypicture.jpg"));
} catch (IOException e) { }
54