Graphics class lets you manipulate the graphics state (such as current color)
Graphics2D class has methods to draw shape objects
Use a cast to recover the Graphics2D object from the Graphics parameter
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
/*
A component that draws two rectangles.
*/
public class RectangleComponent extends JComponent
{
//When the component is shown for the first time, the paintComponent method is called automatically.
//The paintComponent method is called whenever the component needs to be repainted
public void paintComponent(Graphics g)
{
//RecoverGraphics2D
Graphics2D g2 = (Graphics2D) g; //cast
//Construct a rectangle and draw it.
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
//Move rectangle 15 units to the right and 25 units down
box.translate(15, 25);
//Draw moved rectangle
g2.draw(box);
}
}
import javax.swing.JFrame; public class RectangleViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 400); frame.setTitle("Two rectangles"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RectangleComponent component = new RectangleComponent(); frame.add(component); frame.setVisible(true); } }
Compile each java file and run the file with main method.