Java: Summary: Graphics Usage

Subclass JPanel or JComponent to make a "canvas" to draw on.

Call these methods in JComponent or JPanel subclass constructor

Use these calls in the constructor to set the initial values.

setPreferredSize(new Dimension(width, height)); // Set size in pixels.
setBackground(Color c);  // Set background color.   See JComponent vs JPanel.
setForeground(Color c);  // Set the initial pen color. Defaults to black.

Call these methods in paintComponent() to get current size

int w = getWidth();       // Get width of the drawing area
int h = getHeight();      // Get height ...

Extend JComponent or JPanel for drawing

Graphics are usually drawn on a subclass of JComponent or JPanel by overriding the paintComponent method. This class may be defined as an inner class of a JFrame so that it can access the outer class's fields. The constructor should set the size.

class MyDrawing extends JComponent {
    //======================================================= constructor
   public MyDrawing() {
       setPreferredSize(new Dimension(200, 100));
   }
   
   //============================================ override paintComponent
   @Override public void paintComponent(Graphics g) {
       g.setColor(Color.WHITE);           // Set background color
       g.fillRect(0, 0, getWidth(), getHeight());  // Fill area with background.
       setColor(Color.BLACK);             // Restore color for drawing.
       
       g.drawOval(0,0, 100, 100);         // Do your drawing here.
   }
}

Background painting is main difference. The JComponent class doesn't paint its background, so you have to paint the background in the overridden paintComponent method. In contrast, JPanel has an opaque background which can be painted by calling its paintComponennt method as below. You can set the background color of a JComponent, but the JComponent class never uses it.

class MyDrawing extends JPanel {
    //======================================================= constructor
   public MyDrawing() {
       setBackground(Color.WHITE);
       setPreferredSize(new Dimension(200, 100));
   }
    
   //============================================ override paintComponent
   @Override public void paintComponent(Graphics g) {
       super.paintComponent(g);      // Call parent JPanel paintComponent
       
       g.drawOval(0,0, 100, 100);    // Do your drawing here.
   }
}