嗨,专家:我有一个扩展 JPanel 的类,现在 ShapePanel (Sp) 被添加到普通的 JPanel(容器)中,而 JPanel 又被添加到 JFrame(窗口)中。在 PaintComponent 方法中,我绘制了一个形状......但该形状在渲染后永远不会保留。在调试器中,我可以看到每次调整大小或类似的事情时它都会重新绘制。
现在我重载了 JPanel 的(Sp)paintComponent 并添加了这个
super.paintComponent(g);
ShapeDrawerGui SdG = new ShapeDrawerGui((Graphics2D)this.getGraphics());
//for(Shape s : ArrayOfShapes)
{
if(s instanceof Rectangle)
SdG.Paint((Rectangle)s);
else if(s instanceof Triangle)
SdG.Paint((Triangle)s);
else
SdG.Paint((Circle)s);
} //s is a custom-shape object
图形对象(显然)来自 JPanel....
但是绘制的图像永远不会停留在面板上 - 您看到它的瞬间就消失了......
我进行了一些搜索,但没有结果。
实际绘图
public ShapeDrawerGui(Graphics2D _g)
{
g = _g;
g.setColor(Color.Black);
}
@Override
public void Paint(Circle c)
{
g.drawArc(0, 0, 50, 50, 0, 360);
}
@Override
public void Paint(Triangle t)
{
Polygon p = new Polygon();
p.addPoint(0, 25);
p.addPoint(0 , 50);
p.addPoint(50, 50);
g.drawPolygon(p);
}
@Override
public void Paint(Rectangle r)
{
g.drawRect(0, 0, 50, 50);
}
亲切的问候
马库斯
最佳答案
..what is the difference between this.getGraphics and the g ..?
GUI 应在被告知重新绘制时重新绘制,并使用提供给 paint(Graphics)
或 paintComponent(Graphics)< 的
方法。 GUI 可以随时调用该方法,例如在位于另一个窗口后面后重新绘制。Graphics
对象
当您调用 getGraphics()
时,您将获得一个非持久图形对象,该对象将在下次绘制时消失。
关于java - JPanel上绘制对象的持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9774069/