160 likes | 481 Vues
Painting. Paint() and the Graphics Context. Painting . Many components (buttons, scroll bars, etc.) have their appearance determined by the underlying window system. However, applets, frames, panels and canvases, have no given appearance
E N D
Painting Paint() and the Graphics Context
Painting • Many components (buttons, scroll bars, etc.) have their appearance determined by the underlying window system. • However, applets, frames, panels and canvases, have no given appearance • Overloading the paint() method allows us to draw on these components
Painting • Painting a component is done by making calls to a graphics context • For example, g.setColor(Color.BLUE); • Graphics context • Is an instance of the Graphics class • Knows how to render onto a single target.
Painting • The four major operations provided by the Graphics class: • Selecting a color • Selecting a font • Drawing and filling • Clipping
Selecting a Color • There are 13 predefined colors E.g., Color.black, Color.red, Color.blue • If you want a new color: • New Color(R,G,B) • Color c = new Color(255, 0, 0); //red • g.setColor(c); • Call SUBSEQUENT ops will be color c
Selecting a Font • Three fonts are platform independent • Serif • SansSerif • Monospaced • Font f = new Fone(“SansSerif”, Font.BOLD + Font.ITALIC, 24); • g.setFont(f);
Drawing and Filling • Component coordinate system • Point (0,0) is upper-left. • The Graphic Context methods: • drawLine() • drawRect(), fillRect() • drawOval(), fillOval() • drawArc(),
Drawing and filling • drawPolygon() • drawPolyline() • drawString()
drawLine(x1,y1,x2,y2) • Public void drawLine(int x1, int y1, int x2, int y2); • g.drawLine (0,0, 100, 50);
drawRect and fillRect • Public void fillRect(int x, int y, int width, int height); • g.fillRect(20, 25, 100, 80);
drawOval and fillOval • An oval is specified by a rectangular bound ing box • To draw a circle, use a square bounding box.
drawPolyline() • drawPolyline(int x[], int y[], int numberOfPoints); • int pX[] = {20,150,150}; • int pY[] = {20,20,120}; • g.drawPolyline (pX, pY, 3);
Clipping • g.setClip(x, y, width, height);
GUI thread • The Java runtime enviroment creates and controls threads behind the scenes. • One of these threads is the GUI thread. • It accepts user input (mouse) and calls the paint() method
Spontaneous Painting • The GUI thread spontaneously calls paint() whenever a component is • de-iconificatication • After first display
repaint() • If you want to paint something (add a mark to the screen) after a mouse click, do you place the code in the mouse event handler?