Reputation: 1177
I am testing one small widget class that extends JComponent
the constructor for the widget contains one vector and sets PreferredSize of the component, then there is the paintComponent:
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.drawString("this is text one", 10, 10);
//here I draw some shapes based on the
//vector size and integers
}
}
the component is drawn correctly and after that i call some other methods in main, when the methods finish their jobs i call widget.methodsFinished():
methodsFinished(){
g.setColor(Color.GREEN);
g.drawString("this is text two", 30, 30);
this.update(g);
}
I get nullpointer exception by doing this, can you tell me how to correctly update the color of already drawn shapes in this component, thank you in advance.
Upvotes: 0
Views: 5249
Reputation: 15418
can you tell me how to correctly update the color of already drawn shapes in this component, thank you in advance.
Not really so tough:
setShapeColor(Color color)
to set the color to the componentrepaint()
to reflect the color changesAnd as a warning: don't forget to call super.paintComponent(g);
inside the paitnComponent(Graphics)
function, which you haven't done.
class MyComponent extends JPanel
{
private Color shapeColor = Color.RED;
public void setShapeColor(Color color)
{
this.shapeColor = color;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(shapeColor);
g.drawString("this is text one", 10, 10);
//here I draw some shapes based on the
//vector size and integers
}
}
}
Though as OOP principle, you should actually declare a MyShape
class with Color
attribute and before drawing use the setter method as the example to set the color to the shape.
Upvotes: 3