Upload
sylvia-fletcher
View
219
Download
0
Embed Size (px)
Citation preview
Java Dynamic Graphics
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
• Sub-class the component (typically JPanel)• Over-ride paintComponent( ) method
• Custom graphics here
• Can call repaint( ) to invoke paintComponent( )
Codepublic class MyPanel extends JPanel {
public void paintComponent(Graphics g) { super.paintComponent(g); // erases background Graphics2D g2 = (Graphics2D)g; //cast for java2
// my graphics: g2.setColor(new Color(255,150,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 window contents in data structure• E.g. user drawn picture in paint program
• Repaint event:• Erase window (draw background color)• Draw window contents using data structure
• Other event that alters window contents:• modify the data structure• send repaint event
Storing window contents
2 approaches:– Store logical contents in a data structure(s)
• e.g. drawing program: lines, shapes, colors, …
• Then draw contents of data structure
– Store visual contents as an off-screen image (bitmap)
• e.g. pixels
• Then use g2.drawImage( ) in paintComponent( )
Problem: Flashing
• Ugly flashing when repaint:• Paint background
• Erase
• Redraw shapes
Solution: Double buffering
Solution: Double buffering
• Double buffered repaint:• Draw all graphics in temporary off-screen image
• Paint background color• Paint shapes
• Then paint image to JPanel
• Bonus: Swing does this for you!!!• Draw graphics on JPanel• JPanel maintains off-screen image
What Subwindows Do
• Directs mouse input to correct component• Determines repaint events• Own coordinate system• Don’t need repaint when moving• Clipping: hides drawing behind a subwindow
• Some subwindows remember what’s under them:• Popup menus