2D Graphics (with Swing and AWT)

Set up the Panel and Frame

JPanel myPanel = new JPanel() { public void paint (Graphics gra) { Graphics2D g = (Graphics2D) gra; // Cast to child class, which has more methods // Put draw functions here } }; myPanel.setPreferredSize( new Dimension(400,400) ); // Set window size JFrame myFrame = new JFrame(); myFrame.add(myPanel); myFrame.pack(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setVisible(true); myFrame.setLocationRelativeTo(null);
  • You will need to import the following: javax.swing.JFrame, javax.swing.JPanel, java.awt.Graphics, java.awt.Graphics2D, java.awt.Dimension

Set a background color

this.setBackground(Color.blue); super.paint(g);
  • You will need to import java.awt.Color

Draw lines

g.setPaint(Color.green); // Set simple line color g.setStroke(new BasicStroke(3)); // Set line thickness g.drawLine(20, 240, 120, 340); g.drawLine(30, 280, 20, 340);
  • You will need to import java.awt.Color
  • You don't have to set the font or color again, unless they need to change before drawing different lines.

Draw shapes

g.setPaint(Color.black); // Set shape fill/outline color g.setStroke(new BasicStroke(3)); // Set outline thickness // Draw outlines of shapes g.drawRect(100,20,50,60); g.drawOval(170,30,20,40); g.drawArc(200,10,40,30,0,180); g.drawPolygon(new int[]{10,50,90,70,30}, new int[]{50,10,50,90,90}, 5); // Draw solid shapes with fill functions g.setPaint(new Color(20,210,220)); // Custom colors can be defined with their RGB values g.fillOval(50,150,20,40); g.fillRect(10,130,25,35); g.fillArc(80,130,40,30,0,180);
  • The first 2 parameters for rect/oval/arc are the x and y coordinates of the top left corner, and the next 2 coordinates are for width and height.
  • An arc has 2 more parameters for setting start and end angle.
  • For the polygon parameters, you provide the x-coordinates, y-coordinates, and number of points.

Add text

g.setPaint(Color.red); g.setFont(new Font("Serif",Font.PLAIN,40)); g.drawString("Demo text", 200,120);
  • Font must be imported from java.awt

Add images

g.drawImage(new ImageIcon("demoFolder\\demoImage.png").getImage(),200,210,null);
  • The second 2 parameters are the x and y coordinates of the top left corner of the image.
  • ImageIcon must be imported from javax.swing
Completed