Search code examples
javaswingpaintcomponentjcomponent

Java paintComponent()


java paintComponent()

     class MyClass extends JComponent {
         void paintComponent() {
             //code for class here
          }
     }

     class myTestClass extends JPanel {
         MyClass temp = new MyClass();

         void paintComponent() {
               super.paintComponent();


      static void main(String[] a) {
           JFrame f = new JFrame();
              //Does the temp have to be added to the panel before it can be repainted
      } 
     } //End Class

I know that the JPanel goes into the JFrame. But does the class (MyClass) have to be added to the JPanel for the paintComponent() will repaint the child node with super.paintComponent(). I would think that this would be the case. If this is the case then temp.repaint() should repaint that specific component anywhere it is called if the super.paintComponent() repaints the component.

This seems to be an answer that nobody has or at least that nobody really has posted. My explanation might be a little of so I will try and to clarify it here.

If I have several classes that extend JComponent and I want them to all be used in class so I can repaint them. Lets say one is a circle, rectangle, square, and etc..............

If they all have a paintComponent() with a super.paintComponent() they should be able to be repainted with VariableName.repaint();

Do they have to be added to the JPanel that is going to hold them as content. And can they be call to be repaint() be called from anywhere in the code (I think that this is the case).

Driver class:

  class MyMainDriverClass {
    A a = new A();
    B b = new B();
    C c = new C();

void someClass() {
   a.repaint();
   b.repaint();
   c.repaint();  //this should repaint the components if the JPanel is inside of the JFrame 
                 //(I didn't put this code in)
 }
}

This should repaint the component above if all the classes that are created have a paintComponent().

Doug Hauf


Solution

  • Yes MyClass will need to be added to something that is displayable on the screen in order to be painted. The reasoning here is that MyClass extends JComponent and myTestClass extends JPanel, they are in no way related, so calling super.paintComponent from within myTestClass won't paint or update MyClass in any way.

    Any thing you want to be painted must be added to a displayable container.

    Take a look at Painting in AWT and Swing for more details about painting.

    You can call repaint on any Component individual or on it's parent container as required