Drawing over JPanel and adding JPanel to JFrame
I need to draw a graph over a JPanel by overriding JPanel's paintComponent () method.
When developing a gui using netbeans, when I drag the JPanel over the JFrame, it generates code by creating a private JPanel variable. In that case, how can I override its method to draw it ...
otherwise, if I write code for the class, extending the JPanel and overriding the method to draw it, I need to create a new JFrame and add the JPanel to it.
JFrame fr = new JFrame (); fr.add (panel); // pane is a class object that extends the JPanel where I draw fr.setVisible (true);
In this case, it works.
But if I get a link to an auto-generated class that extends the JFrame with a web and uses that to add the JPanel using the add link method, 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 displayed ...
Excuse me if the question is stupid .. im newbie ..
Thanks in advance...
source to share
The behavior of your code is unpredictable because you are violating a basic rule of Swing development: all UI work must be done in the event dispatch thread (EDT) . Your code should look something like this:
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 on the topic here: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
source to share
It looks like you are a beginner using Swing. However, using the JXLayer library makes drawing over components extremely easy and intuitive.
Check out their demo and sample code.
Otherwise great JFreeChart is a great free Java graphics (and visualization) library
source to share