Click here to Skip to main content
15,072,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to draw graphics on a JPanel from inside a separate thread.

The problem is if i try to draw the graphics using a simple method it successfully runs but if i try to do the same thing using thread it does not.

The code is as follows
Java
import java.awt.*;
import javax.swing.*;
public class ttest extends JPanel
{
ttest()
{
JFrame j = new JFrame();
j.setBackground(Color.blue);
j.setSize(200,200);
j.add(this);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
}
protected void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.setFont(new Font("Arial",1,20));
g.drawString("Hello",50,50);
me m = new me(g);
//If i use m.run().. means execute the method simply it draws the string 
//but not if i use m.start() and run it as a new thread.
m.start();//m.run();
}
public static void main(String args[])
{
new ttest();
}
}
class me extends Thread
{
Graphics g;
me(Graphics g)
{
this.g=g;
}
public void run()
{
g.setColor(Color.RED);
g.setFont(new Font("Arial",1,20));
for(int i=0;i<100;i+=20)
{
System.out.println(i);
g.drawString("ME",i,i);
}

}
}


The only problem i can see here is that graphics is being drawn if i use a simple method but not if I make a new thread.
Posted
Comments
TorstenH. 6-Aug-12 4:33am
   
because the other Thread can not access the JPanel - it's occupied by the starting Thread.

Look at Rahul's idea, it's much simpler and pushes the hole JPanel in the Thread.

1 solution

Solved the problem... Rewrote the code as follows...
Java
import java.awt.*;
import javax.swing.*;
public class ttest extends JPanel implements Runnable
{

ttest()
{
JFrame j = new JFrame();
j.setBackground(Color.blue);
j.setSize(200,200);
j.add(this);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
}
int i=10;
protected void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.setFont(new Font("Arial",1,20));
g.drawString("Hello",50,50);
g.drawString("me",i,i);

}
public void run()
{
while(true)
{
i+=20;
repaint();
System.out.println("Hello");
try{Thread.sleep(1000);}catch(Exception e){}
}
}
public static void main(String args[])
{
ttest tt = new ttest();
Thread t = new Thread(tt);
t.start();
}
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900