问题描述
我是油漆/图形的新手,并且想知道如何将JPanel添加到我的代码中,使得整个图形将在JPanel上,而不是在JFrame上。
I'm a newbie to the paint/graphics and wonder how to add a JPanel to my code in such way that the entire graphics will be on a JPanel and not on the JFrame.
换句话说,我正在尝试创建一个允许我这样做的GUI:右边的
显示JPanel上行的良好移动左侧是
,添加一个JTextArea(在JPanel上),它将显示图形的协调性。
In other words, I'm trying to create a GUI that will allow me to do this:on the RIGHT side show the nice movement of the lines on a JPanelon the LEFT side, add a JTextArea (on a JPanel) that will show the coordination of the graphics.
- 这是一个更大问题的简化,但我想这里的代码更容易理解。
谢谢!!!
(下图,移动行或只是运行代码)
(picture below, moving lines or simply run the code)
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();
}
}
推荐答案
- 而不是实现
Runnable
,建立一个ActionListener
,调用repaint()
。从Swing计时器
调用它。 - 有两种方法可以做到这一点。
- 扩展
JComponent
或JPanel
- 在
BufferedImage
中绘制并将其添加到ImageIcon
中的JLabel
。
- 扩展
- Instead of implementing
Runnable
, establish anActionListener
that callsrepaint()
. Call it from a SwingTimer
. - There are 2 ways to do this.
- Extend a
JComponent
orJPanel
- Draw in a
BufferedImage
and add that to anImageIcon
in aJLabel
.
- Extend a
..问题是什么?哦,对,如果可以推断出问题是如何将其他组件与自定义绘制的组件结合起来? - 使用嵌套布局。请参阅。
如果使用 BufferedImage
支持商店,您可以将其放置在该示例中的图像中,除了您将忽略上面的 JTable
,以及 JSplitPane
。
If using a BufferedImage
as backing store, you might place it like the image in that example, except that you would leave out the JTable
above that, as well as the JSplitPane
.
这篇关于如何使用jpanel与油漆(或重绘)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!