我是一个新手绘画/图形,并想知道如何将JPanel添加到我的代码中,这样整个图形将在JPanel上,而不是在JFrame上。如何使用jpanel绘画(或重新绘制)
换句话说,我试图创建一个图形用户界面,可以让我做到这一点: 右侧显示上左侧的JPanel 线的漂亮动作,添加一个JTextArea (在JPanel上)将显示图形的协调。
- 这是一个更大问题的简化,但我猜这里的代码更容易理解。
谢谢!
(如下图,动线或只需运行该代码)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
public class Test extends JFrame implements Runnable
{
private Line2D line;
public Test()
{
super("testing");
this.setBounds(500, 500, 500, 500);
this.setVisible(true);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(line);
}
@Override
public void run()
{
int x=50;
while (true)
{
try
{
Thread.sleep(50);
line = new Line2D.Float(100+x, 100+x, 250-x, 260+x%2);
x++;
repaint();
if (x==5000)
break;
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main (String args[])
{
Thread thread = new Thread (new Test());
thread.start();
}
}
谢谢!我扩展了JPanel,并使用了paintComponent,这个技巧是 – adhg 2011-12-26 19:22:08
,今天我学到了2件东西。再次感谢 – adhg 2011-12-27 01:32:15
不客气。 :-)在这两个方面。 ;) – 2011-12-27 01:47:28