TheCoffeeCup
TheCoffeeCup

Reputation: 326

Draw a Rectangle in Java

I want to draw a rectangle in Java on a Swing application, but I don't know how. I have looked at similar questions, none containing the answer I need. I have tried the following:

private void paintComponent(Graphics graphics, Rectangle rect, Color color) {
    contentPane.paintComponents(graphics);
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.setColor(color);
    graphics2D.draw(rect);
}

I call it like:

contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
paintComponent(contentPane.getGraphics(), new Rectangle(0, 0, 50, 50), Color.WHITE);

But it throws a NullPointerException on this line:

graphics2D.setColor(color);

I suspect it is the graphics2D being null. How can I fix this?

Upvotes: 0

Views: 6254

Answers (1)

Malik Brahimi
Malik Brahimi

Reputation: 16711

You're not even overriding the method correctly. paintComponent only takes a Graphics object as an argument, so you can't add your own.

import javax.swing.*;
import java.awt.*;

public class Test extends JPanel {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new Test());
                frame.setVisible(true);
                frame.pack();
            }
        });
    }

    public Dimension getPreferrdSize() {
        return new Dimension(200, 200);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(10, 10, 150, 40);
    }
}

Upvotes: 3

Related Questions