0

This is my first time encountering GUI's and as I've been learning and searching, I've been trying to do some exercises and i've encountered this error. Would someone please be kind and explain why is this happening? Thank you very much. The error is "Cannot invoke "java.awt.Graphics.setColor(java.awt.Color)" because "g" is null"

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Canvas;
import javax.swing.JFrame;

public class Circle extends Canvas {

    public Circle() {
        JFrame frame = new JFrame("Circle Exercise");
        Canvas paper = new Canvas();
        frame.setSize(500, 500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(paper);
    }
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.RED);
        g.drawOval(100, 100, 200, 200);
    }

    public static void main(String[] args) {
        Circle drawing = new Circle();
        drawing.paint(null);
    }

}
JavaNewbie
  • 57
  • 6
  • Well ... this is the cause: `drawing.paint(null)`. You need to create / obtain a `Graphics` object rather than passing `null`. – Stephen C Jun 26 '21 at 08:24
  • But actually, it is incorrect to draw directly like that. See the answer to https://stackoverflow.com/questions/15986677 for the correct approach. – Stephen C Jun 26 '21 at 08:28

1 Answers1

1
drawing.paint(null); 

Delete that statement it is NOT needed.

Components will automatically be painted whenever Swing determines the component needs to be painted.

However you still have other issues:

  1. The component needs to be added to the frame BEFORE the frame is made visible.

  2. All Components should determine their own preferred size so they can be used properly with layout managers. So you need to override the getPreferredSize() method to return the appropriate size.

  3. Canvas is an older AWT component. People usually paint with Swing components. Typically you would use a JPanel and override the paintComponent(...) method. You then need to invoke super.paintComponent(...) as the first statement to make sure the background is cleared.

  4. Swing components need to be create on the Event Dispatch Thread (EDT) Read the Swing tutorial on Custom Painting for examples that incorporate all the above suggestions to give you better structured code.

camickr
  • 321,443
  • 19
  • 166
  • 288