Java AWT Graphic component is different with respect to x and y coordinate that we have learnt in math. It defines its own coordinate system to specify where and how drawing operation will take place. Here the origin (0,0) is at the top left corner of the component. Here X coordinate increases as we move right and Y coordinate increases as we move down. . The units for X and Y is in pixels.
1. How would you use the Graphics class to draw a line between 2 specific points? Give an example.
To draw a line between 2 points using Java graphics we use a drawLine() method of the graphics class.
Example:
public void draw(Graphics g)
{
g.drawLine(x1,y1,x2,y2);
}
Here the starting point will be (x1,y1) and ending point will be (x2,y2)
2. How do you specify a particular color to be used as fill when using the Graphics class?
Suppose we made a rectangle using the drawRect() method of the graphics class. public void draw(Graphics g)
{
//Rectangle starting point at (100,100) with a height and widht of 80 each
g.drawRect(100,100,80,80);
}
To fill it with a particulat color we first set the color and then call fillRect() method as shown below: public void draw(Graphics g)
{
//Rectangle starting point at (100,100) with a height and width of 80 each
g.drawRect(100,100,80,80);
g.setColor(Color.RED);
g.fillRect(100,100,80,80);
}
3. How would you create a SanSerif font of point size 14 that is bold and italic? Give an example.
public void setFontBoldItalic(Graphics g)
{
Font font=new Font(“SansSerif”, Font.BOLD | Font.ITALIC, 14);
g.setFont(font);
}
4. Given a graphics object g, write a few lines of code to have that graphics object draw a green circle (filled in) that has a diameter of 100 pixels.
public void draw(Graphics g)
{
//Circle starting point at (25,25) with a diameter of 100pixels