Java Graphics: Chris North cs3724: HCI
Java Graphics: Chris North cs3724: HCI
Chris North
cs3724: HCI
Review
• 3 kinds of elements in components API?
• Layout managers
• Events
• Extend vs. Implement
Useful Java DataStructures
• Vector (dynamic array)
• V = new Vector( );
• V.add(item);
• V.elementAt(5);
• HashTable (maps keys to items)
• H = new HashTable( );
• H.add(key, item);
• H.get(key);
• Iterators (automatic FOR loops)
• I = V.iterator( );
• While (I.hasNext( ))
• dosomething(I.next( ));
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
How to Paint?
Pixels
Coordinate System
• Upside-down Cartesian
(0,0) (width,0)
(0,0) JButton
JButton
(wb, hb)
(wp, hp)
Painting Components
• Can paint any component
• JPanel is good for custom graphics area
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
Draw Fill
• Point (x,y)
• Line (pt1,pt2)
• PolyLine (pt list)
• Arc
• Oval (pt, w,h)
• Rectangle (pt, w,h)
• RoundRectangle
Hokie Orange
in Java
• Drawing primitives:
• g2.drawLine( ), .drawRect( ), …
• g2.fillRect( ), …
• Object oriented:
1. Create shape:
• import java.awt.geom.*
• shape = new Point2D.Float(x, y);
• Line2D, Rect2D, CubicCurve2D, …
2. Draw the shape:
• g2.draw(shape);
• g2.fill(shape);
in Java
• Color and font:
• g2.setColor( new Color(r,g,b) );
• g2.setFont( new Font(…) );
• Advanced:
• g2.setStroke(…);
• g2.setPaint(…);
• g2.setComposite(…);
• g2.setTransform(…);
• Repaint event:
• Erase subwindow (fill with background color)
• Draw subwindow contents
In Java
• Repaint event:
• Java Swing components catch repaint event,
and call their paintComponent( ) method
• Default paintComponent( ) method paints component
– E.g. panel background color
// my graphics:
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
Typical program structure for
Dynamic Graphics
• Store data structure of window contents
• E.g. user drawn picture in paint program
• Repaint event:
• Erase window (draw background color)
• Draw window contents using data structure