Change color of JComponent after paintComponent has finished

廉价感情. 提交于 2020-01-06 11:44:09

问题


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:

  1. Declare a private Color field in your class context.
  2. Declare a public setShapeColor(Color color) to set the color to the component
  3. invoke repaint() to reflect the color changes
  4. And 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.



来源:https://stackoverflow.com/questions/20387349/change-color-of-jcomponent-after-paintcomponent-has-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!