Title: 159'234 Lecture 10
1159.234 LECTURE
x
JAVA
Graphics
2Containers and Components
- Component
- Visual object containing text or graphics, which
can respond to keyboard or mouse inputs.
e.g. buttons, labels, text boxes, checkboxes,
lists, canvas
Swing GUI preferred graphical user interface
system to create GUIs in Java 2 because of its
efficiency and flexibility.
All swing components are subclasses of the
abstract class javax.swing.JComponent.
paintComponent method a method common to all
components that handles automatic repainting of
component (if Component is set visible), in
response to actions like dragging, resizing with
a mouse, etc.
3Containers and Components
- Container
- Graphical object that can hold components or
other containers.
- Frame
- area of computer screen surrounded by borders
and a title bar. - most important type of container.
Frame is implemented by class javax.swing.JFrame.
Windows are containers buttons are not.
Containers have special properties, including
layout managers and insets.
4Containers and Components
- Window
- a container with some special properties,
including a locale for managing various human
languages, a toolkit for creating components, and
a warning message for security purposes. - superclass of JFrame
5The graphics class hierarchy
J prefix newer javax.swing package
Object
Component-oriented graphics programming
Component
Button
Canvas
BorderLayout
Checkbox
BoxLayout
Choice
Container
CardLayout
JComponent
CheckboxGroup
JPanel
Color
Window
Graphics
Frame
Graphics2D
and so on
and so on
JFrame
6Building Java Graphics Programs
Screen images are assembled by adding various
components to an instance of the Container class.
x
Container class
Run
The javax.swing.JFrame class provides the
functionality for building graphics programs in
Java. Defined at level 6 in the hierarchy, it
inherits from Frame, Window, Container, Component
and Object.
To learn more about its methods
http//java.sun.com/j2se/1.4.2/docs/api/javax/swin
g/JFrame.html
7Building Java Graphics Programs
Screen images are assembled by adding various
components to an instance of the Container class.
import javax.swing. public class Main
public static void main(String args)
JFrame frame new MainFrame()
frame.show() class MainFrame extends
JFrame MainFrame() setDefaultCloseOperatio
n(JFrame.EXIT_ON_CLOSE) setSize(300,200)
An Empty Window
Instantiation of the MainFrame class
To close the window and terminate the program
See EmptyWindow/Main.java
8Building Java Graphics Programs
Adding more details to the Window
Setting the Title and Location of the Window
import javax.swing. public class Main
public static void main(String args)
JFrame frame new MainFrame()
frame.show() class MainFrame extends
JFrame MainFrame() setDefaultCloseOperatio
n(JFrame.EXIT_ON_CLOSE) setSize(300,200)
setTitle("Tank Game") setLocation(250,
150) //setLocation(x, y)
o
y
x
Setting the Title and Location
See WindowTitle/Main.java
9Building Java Graphics Programs
Centering the Window on Screen
import javax.swing. import java.awt. public
class Main public static void main(String
args) Dimension screenSize
Toolkit.getDefaultToolkit().getScreenSize()
int w screenSize.width int h
screenSize.height JFrame frame new
MainFrame(w/2,h/2,w/4,h/4) frame.show()
class MainFrame extends JFrame
MainFrame(int width, int height, int x, int y)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setSize(width,height) setTitle("Tank
Game") setLocation(x, y)
Defines Dimension and Toolkit classes.
Modified constructor
See CenteredWindow/Main.java
10Building Java Graphics Programs
Centering the Window on Screen
Displaying Text in a Graphics Window
ContentPane of JFrame
JLabel
Napoleon
JFrame
A JLabel object can be directly added to JFrame
JFrame has a ContentPane
See JLabel/Main.java
11Building Java Graphics Programs
import java.awt. import javax.swing. public
class Main public static void main(String
args) Dimension screenSize
Toolkit.getDefaultToolkit().getScreenSize()
int w screenSize.width JFrame frame new
MainFrame(w/5, 100, 2w/5,0) frame.show()
class MainFrame extends JFrame
MainFrame(int width, int height, int x, int y)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setTitle("Main Frame") setSize(width,
height) setLocation(x,y) JLabel label
new JLabel("Napoleon") label.setFont(new
Font("Serif", Font.BOLD Font.ITALIC, height/2
)) label.setForeground(Color.red)
getContentPane().add(label)
JLabel object on top of a JFrame container
Javax.swing.JLabel CLASS
Instantiating a JLabel object
Adding the JLabel object to the ContentPane of
the JFrame class
See JLabel/Main.java
12Using a JPanel Container
JLabel object on JPanel, on JFrame container
Javax.swing.JLabel CLASS
ContentPane of JFrame
JLabel
Napoleon
JPanel
Intermediate container
JFrame
A JLabel object can be directly added to JFrame,
but most of the time, we would want it to appear
on top of a JPanel object, which lies on top of a
JFrame container.
JFrame has a ContentPane
See JPanel/Main.java
13Setting the Color
Java.awt.Color CLASS
For JPanel and JLabel objects, java.awt.Component
class defines the following methods
e.g. Color.red
public void setBackground(java.awt.Color c)
public void setForeground(java.awt.Color c)
Public static final Color fields Cyan,
darkGray, lightGray, gray, green, magenta, pink,
orange, yellow, white, black
Integer values 0, 255
setBackground(new Color(r, g, b))
e.g.
256256256 16,77,216 possible colors
Gold (255,215,0), Purple (160, 32, 240)
See JPanel/Main.java
14JButton objects
Java.awt.event.Action CLASS
Java.util.Listener objects can detect input
events and respond to them.
JButton exitButton new JButton(Exit)
Create an instance
exitButton.addActionListener(new Listener())
class Listener implements ActionListener
Listener() // user codes public
void actionPerformed(ActionEvent event) //
user codes
Will have to be implemented by user
Automatically invoked by the Java run-time system
See JButton/Main.java
15JButton objects
Sample code Attaching JButton objects to a
JPanel Container
class ButtonPanel extends JPanel
ButtonPanel() add(helpButton,
BorderLayout.CENTER) helpButton.addAction
Listener(new GameAction(H)) //
class GameAction implements ActionListener
private char action GameAction(char a)
action a public void
actionPerformed(ActionEvent event)
switch(action) case H
label.setText(Help) break //
//GameAction //ButtonPanel
Being an inner class, GameAction objects can be
instantiated here.
Run
Inner class
See JButton/Main.java
16Displaying Graphics on a Component
Basic steps required to display graphics in Java
1. Create the component or components to display.
- Create a frame to hold the component(s), and
place the component(s) into - the frame.
- Create a listener object to detect and respond
to mouse clicks, and assign - the listener to the frame.
without the listener, we could never close a
frame, once it was created.
A simple program that displays the basic skeleton
required to create Java graphics.
See JCanvas.java
17Creating and Displaying a Frame and a Component
- Create a subclass of JComponent and override the
paintComponent method to display the data you
want.
Every Swing component is a subclass of
JComponent. Class JComponent is an abstract
class, and method paintComponent is an abstract
method within that class.
import java.awt. import java.awt.event. import
java.awt.geom. import javax.swing. public
class DrawLine extends JComponent
//constructor public DrawLine()
setDoubleBuffered(true) //
//this method extends JComponent and draws a line
//on the component public void
paintComponent(Graphics g) Graphics2D g2
(Graphics2D) g //draw your objects here
Details shown in next slide.
Sets the component to use double buffering, which
means that the component has memory for two
complete sets of graphical images.
18Creating and Displaying a Frame and a Component
- Create an object of type Graphics2D inside the
paintComponent method to utilize all the tools in
the java.awt.geom package for drawing graphics
on screen.
//this method extends JComponent and draws a
line on the component public void
paintComponent(Graphics g) Graphics2D g2
(Graphics2D) g //set background color
Dimension size getSize()
g2.setColor(Color.white ) g2.fill(new
Rectangle2D.Double(0,0,size.width,size.height
)) //draw line g2.setColor(Color.black
) Line2D line new Line2D.Double(10.,10.,360
.,360.) g2.draw(line)
The paintComponent method always has the calling
sequence paintComponent(Graphics g) for
backward compatibility with earlier versions of
Java.
See DrawLine.java
Class DrawLine extends JComponent and draws a
single Line on a white background.
19To draw lines in Java
- Select a line color using the Graphics2D setColor
method. - Select a line width and line style using a
BasicStroke object, and associate that basic
stroke with the line using the Graphics2D
setBasicStroke method. - Set the endpoints of the line using a
Line2D.Double or Line2D.Float method, and draw
the line with a call to the Graphics2D draw
method.
Color.orange, Color.darkGray, color.pink, etc.
Parameters Line width in pixels, shape of line
end caps, shape of decorations where two line
segments meet, style of the line (solid, dashed,
dotted, etc.)
Line2D.Double(double x1, double y1, double x2,
double y2)
20The TankGame in Java
Putting the pieces together in a Java Graphics
Game
- Features
- keyboard support
- button objects
- 2D animation
Double-buffering is automatically supported
Equipped with a rich set of graphics functions
Anti-aliasing of graphic objects also provided
See JGame/Main.java
21The TankGame in Java
JFrame
KeyListener
JComponent
Sprite
JPanel
Tank
JLabel
paintComponent
JPanel
Graphics2D
JButton
Tank.draw
addActionListener
See JGame/Main.java
22The TankGame in Java
MainFrame
JFrame
Public Sprite Tank
KeyListener
JCanvas
MainPanel
JComponent
Sprite
JPanel
Tank
JLabel
Ellipse2D, Arc2D, RoundRectangle2D
ButtonPanel
paintComponent
JPanel
Graphics2D
JButton
Tank.draw
addActionListener
See JGame/Main.java