-4

I know this has been told many times but I've been programming with java for about 3 weeks and I've just been having some fun making stuff. Most of the other reports people have made did not fix my problem. The screen displays but not the rect. Here is my code:

import java.awt.Rectangle;
import javax.swing.JFrame;
import java.awt.Color;

public class something {
    public static int SCREEN_WIDTH = 500;
    public static int SCREEN_HEIGHT = 500;
    public static int Y = 10;
    public static int X = 10;
    public static int Width = 50;
    public static int Height = 50;
    public static Color player_color = Color.black;
    public static Graphics g;

    public static void screen() {
        JFrame screen = new JFrame();
        screen.setVisible(true);
        screen.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screen.setTitle("test");
        screen.setResizable(false);
    }

    public static void player() {
        Rectangle r = new Rectangle(Y, X, Width, Height);
        g.fillRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
        g.setColor(player_color);
    }

    public static void main(String[] args) {
        screen();
        player();
    }
}

By the way I am using Eclipse and I think the problem means I'm using a value which has a null value? Correct me if I'm wrong.

danny
  • 3
  • 2
  • `g` is `null`. Don't make everything `static`. – Elliott Frisch Mar 10 '20 at 17:15
  • Because the Graphics class is an abstract base class, it cannot be instantiated directly. An instance is typically created by a component, and handed to the program as an argument to a component's update() and paint() methods. – Nils Mar 10 '20 at 17:28
  • I think you need to create Canvas first and then you can draw Rectangle in it. ``` Canvas c = new Canvas(); g = c.getGraphics(); ``` – Nils Mar 10 '20 at 17:37

1 Answers1

0

Your g is null and not initialized to anything so you are getting nullpointer while accessing fillRect() method.

You can just use extends Applet at class level and override paint method().

public class something extends Applet {
    public static int SCREEN_WIDTH = 500;
    public static int SCREEN_HEIGHT = 500;
    public static int Y = 10;
    public static int X = 10;
    public static int Width = 50;
    public static int Height = 50;
    public static Color player_color = Color.black;

    @Override
    public void paint(Graphics g) {
        JFrame screen = new JFrame();
        screen.setVisible(true);
        screen.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screen.setTitle("test");
        screen.setResizable(false);
        Rectangle r = new Rectangle(Y, X, Width, Height);
        g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(), (int) r.getHeight());
        g.setColor(player_color);
    }