Download Lecture 25: Graphics in Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lecture 25: Graphics in Java
CS 170, Section 000
3 December 2009
12/3/2009
CS170, Section 000, Fall 2009
1
Lecture Plan
™Homework 8 details review
¾More on GUIs
¾ More on Java GUI API (Ch. 13):
¾ Essential Swing components and layouts
¾Putting it all together: TicTacToe
¾GUI very similar
i il to HW8
ƒ Homework
H
k 8 questions
ti
CS170, Section 000, Fall 2009
2
HW8: Game of Life
• A mathematical game invented by mathematician John Conway
in 1970
• Game rules
– A dead cell with exactly three live neighbors becomes a live cell (birth).
– A live cell with two or three live neighbors
g
stays
y alive (survival).
(
)
– In all other cases, a cell dies or remains dead (overcrowding or
loneliness).
• Resources and demos
– http://www.math.com/students/wonders/life/life.html
– http://www.ibiblio.org/lifepatterns/
• Implementation
– Use Timer class for animation
– Use two dimensional arrays for cell updates, then drawImage!
¾ Even better: draw each cell separately (as JPanel like TicTacToe example
– stay tuned)!
GUI Class Hierarchy (Swing)
Dimension
Font
Classes in the java.awt
package
LayoutManager
1
Heavyweight
FontMetrics
Object
Color
Panel
Applet
JApplet
Wi d
Window
F
Frame
JF
JFrame
Dialog
JDialog
Graphics
C
Component
C
Container
i
*
Swing Components
in the javax.swing package
JComponent
Lightweight
4
Container Classes
Dimension
Font
Classes in the java.awt
package
LayoutManager
1
Heavyweight
FontMetrics
Object
Color
Panel
Applet
JApplet
Window
Frame
JFrame
Dialog
JDialog
Graphics
Component
p
Container
*
JComponent
Container classes can contain
other GUI components.
Lightweight
5
JPanel
Swing Components
in the javax.swing package
Swing GUI Components
JCheckBoxMenuItem
Ab
AbstractButton
JComponent
JMenuItem
JMenu
JButton
JRadioButtonMenuItem
JToggleButton
JCheckBox
JRadioButton
JEditorPane
JTextComponent
JTextField
JPasswordField
JTextArea
JLabel
JTabbedPane
JToolBar
JTree
JComboBox
JList
JSplitPane
JMenuBar
JTable
JPanel
JLayeredPane
JJPopupMenu
p p
JTableHeader
6
JOptionPane
JSeparator
JJFileChooser
C
JInternalFrame
JScrollBar
JSlider
JScrollPane
JRootPane
JColorChooser
JProgressBar
JToolTip
p
JSpinner
Frames
• Frame is a window that is not contained inside
another window. Frame is the basis to contain
other user interface components in Java GUI
applications.
• The JFrame class can be used to create
windows.
• For Swing GUI programs, use JFrame class to
create widows.
7
Creatingg Frames
import javax.swing.*;
public class MyFrame {
public static void main(String[]
p
(
g[] args)
g ) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400, 300);
frame.setVisible(true);
frame setDefaultCloseOperation(
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
8
Adding Components into a Frame
Title bar
// Add a button into the frame
frame.getContentPane().add(
new JButton("OK"));
JButton( OK ));
Content pane
9
Layout
y
Managers
g
• Java’s layout managers provide a level of abstraction to
automatically
i ll map your user iinterface
f
on allll window
i d
systems.
• The UI components are placed in containers. Each
container has a layout
y
manager
g to arrange
g the UI
components within the container.
• Layout managers are set in containers using the
setLayout(LayoutManager) method in a container.
10
Kinds of Layout
y
Managers
g
• FlowLayout (Chapter 13)
• GridLayout (Chapter 13)
• BorderLayout (Chapter 13)
• Several other layout managers will be introduced
in Chapter 33, “Containers, Layout Managers, and
Borders”
11
FlowLayout Example
Write a program that
adds three labels and
text fields into the
content pane of a
frame with a
FlowLayout manager.
12
GridLayout Example
Rewrite the program in
the p
precedingg example
p
using a GridLayout
manager instead of a
FlowLayout manager to
display the labels and
text fields.
Sh GridL
ShowGridLayout.java
ut j
13
The GridLayout Class
java.awt.GridLayout
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
-rows: int
The number of rows in this layout manager (default: 1).
-columns: int
Th number
The
b off columns
l
in
i this
thi llayoutt manager (d
(default:
f lt 1).
1)
-hgap: int
The horizontal gap of this layout manager (default: 0).
-vgap: int
The vertical gap of this layout manager (default: 0).
+GridLayout()
Creates a default GridLayout manager.
+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
g p int,, vgap:
g p int))
hgap:
columns,, horizontal g
gap,
p, and vertical ggap.
p
14
Using Panels as Sub-Containers
• Panels act as sub-containers for ggrouping
p g user
interface components.
• It is recommended that you place the user interface
components in panels and place the panels in a frame.
place p
panels in a p
panel.
You can also p
• To add a component to JFrame, you actually add it to
the content pane of JFrame. To add a component to a
panel, you add it directly to the panel using the add
method.
15
Creating a JPanel
You can use new JPanel() to create a panel with a default
FlowLayout manager or new JPanel(LayoutManager) to
create a panel with the specified layout manager. Use the
add(Component)
dd(
) method
h d to add
dd a component to the
h
panel. For example,
JPanel p = new JPanel();
p.add(new JButton("OK"));
16
Testing Panels Example
This example uses panels to organize components.
The program creates a user interface for a
Microwave oven.
frame
A textfield
p2
2
A button
12
buttons
p1
TestPanels
17
More on JPanel
• http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JPanel.html
• Exercise for the reader: set color of a panel
12/3/2009
CS170, Section 000, Fall 2009
18
Event Classes
EventObject has
getSource()
method, which
j
returns the object
that generated
this event.
The subclasses
have other
methods that
describe the
event further
EventObject
AWTEvent
ActionEvent
ComponetEvent
InputEvent
MouseEvent
KeyEvent
WindowEvent
Listeners
• Some listeners have multiple methods
–
–
–
–
–
–
–
–
public abstract interface MouseListener
extends EventListener {
publicc abstract
pub
abs ac void
o d mouseClicked(MouseEvent
ouse c ed( ouse e e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
e)
public abstract void mouseReleased(MouseEvent e);
};
• Classes that implement interfaces
– MUST define code for all methods of the interface
• If you only need code in one method, solution isn't clean
20
Handling Mouse Events
– import java.applet.Applet;
– import java.awt.*;
– import java.awt.event.
java.awt.event.*;;
– public class AkmMimic extends Applet {
– public void init () {
–
this.add (new TextField(20));
–
thi dd (new
this.add
(
LLabel
b l ("N
("No news is
i good
d news"));
"))
–
this.add (new Button("OK"));
–
this.addMouseListener (new MyMouseHandler());
– }
– }
– class MyMouseHandler implements MouseListener {
– public void mouseClicked(MouseEvent e) { }
– public void mouseEntered(MouseEvent e) { }
– public void mouseExited(MouseEvent e) { }
– public void mousePressed(MouseEvent e) {
–
System.out.println ("You pressed a mouse button");
– }
– public void mouseReleased(MouseEvent e) { }
– }
21
Using Adapters to Listen
• For most listeners, there is a corresponding adapter
–
–
–
–
–
–
–
class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
• You can reuse these,
h
and only
l implement
l
necessary
methods
–
–
–
–
–
class MyMouseHandler
y
extends MouseAdapter
p {
public void mousePressed (MouseEvent e) {
System.out.println ("You pressed a mouse button");
}
}
22
Using MouseAdapter
import java.applet.Applet;
import java.awt.*;
i
import
j
java.awt.event.*;
*
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));
this.add (new Button("OK"));
this.addMouseListener ((new MyMouseHandler());
y
());
}
}
class MyMouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
System.out.println ("You pressed a mouse button");
}
}
23
Event adapters
• A listener must implement all the methods in the
corresponding listener interface
– Sometimes too tedious
• Provide Adapter class so that user don’t need to define every
method,, onlyy the one interested in
public interface MouseListener{
void mouseClicked(MouseEvent e);
void mouseEntered(MouseEvent e);
void mouseExited(MouseEvent e);
void mousePressed(MouseEvent e);
void mouseReleased(MouseEvent e);
}
public class MouseAdapter implements MouseListener{
//define all the five methods above, but all do nothing
}
Class MyMouseListener extends MouseAdapter { … }
Putting it All Together: TicTacToe
JPanel
Cell
-token:
token: char
T k usedd in
Token
i the
th cell
ll (default:
(d f lt ' ').
')
+getToken():char
Returns the token in the cell.
+setToken(token: char): void
Sets a new token in the cell.
#paintComponent(g:
p
p
(g Graphics):
p
) void
Paints the token in the cell.
+mouseClicked(e: MouseEvent): void
Handles a mouse click on the cell.
25
Case Study: TicTacToe, cont.
Cell
JApplet
9
1
TicTacToe
-whoseTurn:
whoseTurn: char
Indicates which player has the turn,
turn initially 'X'
X.
-cell: Cell[][]
A 3 by 3, two dimensional array for cells.
-jlblStatus: JLabel
A label to display game status.
+TicTacToe()
Ti T T ()
C
Constructs
the
h Ti
TicTacToe
T T user interface.
i
f
+isFull(): boolean
Returns true if all cells are filled.
+isWon(token: char): boolean
Returns true if a player with the specified token has won.
TicTacToe.java
26
Converting to/from Applications and Applets
• You can always convert an applet into an application
application.
– Implement the main() method
– Create a JFrame to hold the applet
– Must explicitly start the applet
• You can convert an application to an applet as long as
security restrictions are not violated.
27
Summary
¾Essential Java GUI
¾Layout (Flaw, Grid, Border, etc)
¾Components (buttons, panels, etc)
¾Putting it all together: TicTacToe.java
ƒ Extending JPanel
ƒ Layout components in a grid
ƒ Handling
H dli M
Mouse eventt
CS170, Section 000, Fall 2009
28
Remaining HW8 questions?
• A mathematical game invented by mathematician John Conway
in 1970
• Game rules
– A dead cell with exactly three live neighbors becomes a live cell (birth).
– A live cell with two or three live neighbors
g
stays
y alive (survival).
(
)
– In all other cases, a cell dies or remains dead (overcrowding or
loneliness).
• Resources and demos
– http://www.math.com/students/wonders/life/life.html
– http://www.ibiblio.org/lifepatterns/
• Implementation
– Use Timer class for animation
– Use two dimensional arrays for cell updates, then drawImage!
¾ Even better: draw each cell separately (as JPanel like TicTacToe example
– stay tuned)!
Extra Material: Graphics
• HW 9: Use graphics to visualize MIDI music files
• Read Ch. 15
• How you can get famous with simple Java (in ‘96)
– http://www.cooper.edu/~agicht/3dplot/test.html
http //www cooper edu/~agicht/3dplot/test html
12/3/2009
CS170, Section 000, Fall 2009
30