Java – Drawing over a JPanel and adding the JPanel to JFrame

graphicsjavajframejpanelpaint

I need to draw a graph over a JPanel by overriding the JPanel's paintComponent() method.

While designing gui using netbeans when i drag/drop a JPanel over JFrame it generates code by creating a private variable, JPanel object. In such a case how can i override its method to draw over it…

or else if i write code for a class by extending the JPanel and override the method to paint it, I have to create a new JFrame and add the JPanel to it..

JFrame fr=new JFrame();
fr.add(pane); //pane is the object of class that extends JPanel where i draw
fr.setVisible(true);

In this case it works..

But if i get a reference of the auto-created class which extends JFrame by netbeans and use that to add the JPanel using the add method of the reference got it doesn't work…

class x extends JPanel 
{ 
       paintComponent(Graphics g){         //overridden method 

           //my code for drawing say lines goes here.. 
           } 
} 

class y extends Thread 
{ 
         z obj; 

         y(z obj){ 

          this.obj=obj; 
          } 
         public void run(){ 

              x pane=new x(); 
              pane.setVisible(true); 
              obj.add(pane); 
              obj.setVisible(true);         //im not getting the pane visible here.. if i created a new JFrame class here as i said earlier and added the pane to it i can see it.. 
            } 
} 

class z extends JFrame 
{ 
            z(){//code generated by netbeans} 

           public static void main(String args[]) 
           { 


                    new y(new z()).start(); 
           } 
}

It shows no error but when i run the program only the Jframe is visible.. JPanel is not shown…

Pardon me if the question is silly.. im a beginner..

Thanks in advance…

Best Solution

Behavior of your code is unpredictable because you are violating main rule of Swing development: all UI work should be done on Event Dispatch Thread (EDT). Your code should look something like:

public static void main(String args[]) { 
    SwingUtilities.invokeLater( new Runnable() {
         void run() 
         {
             JFrame z = new JFrame();
             z.add(new X()); // works only in java 6
            //z.getContentPane().add(new X()); // works in any version of java
             z.pack(); // assuming your pane has preferred size 
             z.setVisible(true); 

         }
    }); 
}

More about the subject is here: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

Related Question