Search code examples
javaswingcolorspaintcomponentjcomponent

Change color of JComponent after paintComponent has finished


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.


Solution

  • 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.