CSC223, Class 27: Swing (3): Graphics (Briefly) Admin: * Late: Louisa * Missing: Kat, Evan, Omondi, Luis * Exam now due Monday. * Questions on the exam? Bring them Friday! * Is the PolySci event still going on? Overview: * Basics * Typical steps * Examples /Graphics Basics/ * Graphics in a user interface are hard (or at least have a lot of complicating issues) * How do you know when to draw? * When an event happens in the window (e.g., user types or clicks) * When something embedded within the window changes (e.g., image in a Web page) * When the window is changed (e.g., resized, expanded from compressed version) * When another window moves over it * When program code indicates it is necessary (e.g., animation) * ... * How do you handle all these different possibilities? * Redraw every N units of time: Inefficient * Hope that the "world" tells you when its time to redraw (Swing provides this) * What do you redraw? Only the portion of interest * Smart systems tell you what the "portion of interest" is * Smart systems ignore drawing commands outside the "portion of interest" * How do you deal with nested or overlapping objects? * You want your windowing toolkit to deal with this, too * In AWT, components override the paint(java.awt.Graphics) method * Problem: Expected programmer to deal with nesting * In Swing, components override the paintComponent(java.awt.Grapics) method * The paint method in JComponent does the smart thing * Painting model: * The point (0,0) is upper-left * Increasing x goes to the right * Increasing y goes down /How do you write a paintComponent() method?/ public void paintComponent(Graphics brush) { * Step one (usually): Figure out the bounds of this component java.awt.Rectangle bounds = this.getBounds() int x = bounds.getX(); int y = bounds.getY(); int w = bounds.getWidth(); int h = bounds.getHeight(); * Alternate int x = this.getX(); int y = this.getY(); int w = this.getWidth(); int h = this.getHeight(); * Step two (sometimes, for efficiency), Figure out the "clip region" (the portion that is being drawn) Rectangle bounds = brush.getClipBounds() * Repeat the following steps as often as necessary * Step threea: Choose a color to draw with brush.setColor(java.awt.Color) * Step threeb: Draw something brush.fillRect(...) brush.fillOval(...) ... * Sometimes: Call the method in the superclass super.paintComponent() (first, last, middle, never) /Example/ * Warning! Currently doesn't work right.