package Graphics; import java.awt.*; import java.awt.geom.Line2D; import java.util.Random; import javax.swing.*; // JPanel class for drawing in // has main to bootstrap itself in a window public class MyPicture extends JPanel { // automatically called when a JPanel is drawn onscreen public void paintComponent(Graphics g) { // let JPanel do its own drawing work super.paintComponent(g); // to simplify code, pull out height and width of the JPanel. final int H = getHeight(); final int W = getWidth(); // fill in background color setBackground(Color.WHITE); // set the color we are using to a new color (R, G, B) // change the color on the paintbrush g.setColor(new Color(100,150,200)); // draw rectangles in the current color g.fillRect(20, 30, 80, 90); // filled (80 x 90 pixels, starting at x=20, y=30) g.drawRect(10, 20, 100, 140); // outline g.setColor(Color.BLUE); // blue // draw ovals g.fillOval(400, 10, 60, 190); // filled round g.drawOval(280, 20, 200, 70); // outline g.setColor(Color.MAGENTA); // draw a line from (W, 0) to (0, H) g.drawLine(W, 0, 0, H); g.setColor(Color.PINK); // choose font to use g.setFont(new Font("Times New Roman", Font.PLAIN, 64)); // draw text g.drawString("HELLO", 50, 90); g.drawString("WORLD!", 220, 140); // Graphics we were given is really a Graphics2D object, used for fancier graphics Graphics2D g2 = (Graphics2D) g; // magic paint that starts as RED at W/2,H/2 and shades to BLUE at W,H GradientPaint gradi = new GradientPaint(W/2, H/2, Color.RED, H, W, Color.BLUE); // set to use the magic paint to draw g2.setPaint(gradi); // based on number of circles, figure out how big each one is int howmany = 10; int xoffset = W / 2 / howmany; int yoffset = H / 2 / howmany; // nested loops to draw grid of circles for (int i = W/2; i < W - xoffset; i = i + xoffset) { for (int j = H/2; j < H - yoffset; j = j + yoffset) { // draw filled oval at current position, filling not quite all space to next one g2.fillOval(i, j, xoffset - 10, yoffset - 10); } } // we will be drawing random lines, but want them to join up // so keep some endpoints int x1 = 0; int y1 = W; Random rand = new Random(); // set the way lines will be drawn // in this case, width of line is 2 pixels g2.setStroke(new BasicStroke(2)); // 100 random lines for (int i = 0; i < 100; i++) { // random color for next line g2.setPaint(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))); //new random end point int x2 = rand.nextInt(W/2); int y2 = H/2 + rand.nextInt(H/2); // draw a line object that uses the stroke we set (and can use double coordinates) g2.draw(new Line2D.Double(x1, y1, x2, y2)); // update the end point x1 = x2; y1 = y2; } } // create a window and put the JPanel in it public static void main(String[] args) { JFrame win = new JFrame("Picture"); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); win.add(new MyPicture()); win.setSize(500,500); win.setVisible(true); } }