Search code examples
javaswingnullpointerexceptionjpaneljava-2d

Using graphics on a JPanel


I'm trying to draw a rectangle to a JPanel using the following code:

JPanel background = new JPanel();
Graphics2D g = null;
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 800, 600);

When I try to compile it I get the error

java.lang.NullPointerException on the set colour line.

I have also tried this but i get the same bug

JPanel background = new JPanel();
Graphics bg = background.getGraphics();
bg.setColor(Color.BLACK);
bg.drawRect(0, 0, 800, 600);

can anyone help me fix this bug?


Solution

  • To draw on a JPanel, you need to override paintComponent(). You can override it on the fly as follows or create a subclass:

    JPanel background = new JPanel()
    {
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.BLACK);
            g2d.drawRect(0, 0, 800, 600);
        }
    };