Download presentation
1
Java Dynamic Graphics
2
In Java Repaint event: Sub-class the component (typically JPanel)
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( )
3
Code Hello World public 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
4
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
5
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( )
6
Problem: Flashing Ugly flashing when repaint: Paint background Erase
Redraw shapes
7
Solution: Double buffering
8
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
9
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.