Reputation: 142
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?
Upvotes: 0
Views: 341
Reputation: 347184
Custom painting in Swing is normally done by overriding the paintComponent method of any class that extend JComponent. Unless you have some need to do otherwise, it is recommended that you extend from something like a JPanel.
public class MyPanel exends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(0, 0, 800, 600);
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
}
Take a look at Performing custom painting and 2D Graphics for more details
Upvotes: 3
Reputation: 691635
Create a subclass of JPanel, and override the paintComponent(Graphics g)
method. Only paint from this method, using the Graphics
passed as argument to the method, that you can safely cast to Graphics2D
:
JPanel background = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 800, 600);
}
}
Upvotes: 4
Reputation: 117579
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);
}
};
Upvotes: 5