本文介绍了从单独的线程在JPanel上绘制图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从单独的线程内部在JPanel上绘制图形.
问题是,如果我尝试使用简单的方法绘制图形,则它可以成功运行,但是如果我尝试使用线程进行相同的操作,则不会.
代码如下
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
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.
推荐答案
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();
}
}
这篇关于从单独的线程在JPanel上绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!