问题
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.
回答1:
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:
- Declare a private Color field in your class context.
- Declare a public
setShapeColor(Color color)
to set the color to the component - invoke
repaint()
to reflect the color changes And as a warning: don't forget to call
super.paintComponent(g);
inside thepaitnComponent(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.
来源:https://stackoverflow.com/questions/20387349/change-color-of-jcomponent-after-paintcomponent-has-finished