Java GUI
1. Introduction2. Java Graphics
GUI in a nutshell
Other topics: Drawing Capabilities
XuanTung Hoang 4
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()
XuanTung Hoang 5
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
XuanTung Hoang 6
Our own panel class
XuanTung Hoang 7
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
XuanTung Hoang 8
Getting drawing area from Graphics object
Rectangle class
Rectangle r specifies drawing area of Graphics object g in current drawing context coordinate system
XuanTung Hoang 9
Drawing using Graphics object
XuanTung Hoang 10
Put our drawing panel into a frame and show the frame NOTE: setLayout before adding drawing panel
XuanTung Hoang 11
Output
XuanTung Hoang 12
We can add more GUI components to control drawing
How ?
XuanTung Hoang 13
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
(x, y)
length
LEFT = 0 RIGHT = 1
DOWN = 2
UP= 3
dir
(0, 0)
(MAXX, MAXY)
XuanTung Hoang 14
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);
XuanTung Hoang 15
Example: Display cards on Panel