150 likes | 331 Views
Spring 2009 Programming Fundamentals I Java Programming. XuanTung Hoang tung_hx@icu.ac.kr. Lecture No. 18. Java GUI. Introduction Java Graphics. GUI in a nutshell. Other topics: Drawing Capabilities. Drawing on a panel. Sometimes it is necessary to paint on a GUI component
E N D
Spring 2009 Programming Fundamentals IJava Programming XuanTung Hoang tung_hx@icu.ac.kr Lecture No. 18
Java GUI Introduction Java Graphics
GUI in a nutshell Other topics: Drawing Capabilities
Drawing on a panel • Sometimes it is necessary to paint on a GUI component • For example: Paint on a JPanel, paint on a JButton, … • How to paint on a GUI component? • Create a subclass of the component (inheritance) • Override paintComponent(Graphics g)method • The argument g is the object that provide drawing capabilities • Use the object g to paint • Frequently used methods: getClipBounds(), setColor(), getColor(), clearRect(), drawRect(), fillRect(), drawLine(), drawOval()
Example: Drawing on a Panel • Create our own panel class by extending JPanel • Override paintComponent() method and put our drawing code there • Create our own frame and use our panel class as a Swing component
Graphics class: • Class that represents “graphic contexts” • The area that paintComponent() will draw on • Control font styles/line patterns/fill patterns/colors • Provide drawing support methods
Rectangle class • Getting drawing area from Graphics object Rectangle r specifies drawing area of Graphics object g in current drawing context coordinate system
Put our drawing panel into a frame and show the frame • NOTE: setLayout before adding drawing panel
Example: Make a snake that runs • We will make a snake that runs across a panel • Solution: • A snake = a horizontal line = a point (x, y) (the head) , a length, and a direction • We use a timer, after each timer event we change position of the head and repaint the snake on a panel (0, 0) dir (x, y) LEFT = 0 RIGHT = 1 length DOWN = 2 UP= 3 (MAXX, MAXY)
Render and image on a panel • Import java.awt.image.* • Import javax.imageio.* • Create a BufferedImage object using static method read of ImageIO class • BufferedImage img = ImageIO.read(new FileInputStream(“Image.jpg” )); • Draw the image with drawImage() method of class Graphics • g.drawImage(img, x, y, width, height, null);