[英]how to draw graphics in JPanel out of paintComponent method?
i need to draw some lines in a JPanel
in Java, I'm trying to draw them in another method outside the paintComponent()
method to call it from another class but i faced a problem because drawing graphics need a Graphics
object, i tried using this.getGraphics()
but didn't work for me : 我需要在Java的
JPanel
中绘制一些线,我试图在paintComponent()
方法之外的另一个方法中绘制它们,以从另一个类调用它,但是我遇到了一个问题,因为绘制图形需要一个Graphics
对象,因此我尝试使用this.getGraphics()
但对我不起作用:
public class Panel extends JPanel{
public void drawLine(int x1, int y1, int x2, int y2){
this.getGraphics().drawLine(x1, y1, x2, y2);
}
}
any suggessions please ? 有什么建议吗?
"any suggessions please ?"
“有什么建议吗?”
Keep a list of Line2D
objects in the Panel
class. 在
Panel
类中保留Line2D
对象的列表。 ( List<Line2D>
) (
List<Line2D>
)
Iterate through the list in the paintComponent
method 遍历
paintComponent
方法中的列表
Graphics2D g2 = (Graphics2D)g;
for (Line2D line : lines) {
g2.draw(line);
}
Then you can just have a method to addLine(Line2D line)
, which adds a line to the list and repaint()
s 然后,您可以有一个方法
addLine(Line2D line)
,这会将一条线添加到列表中,并repaint()
s
public void addLine(Line2D line) {
lines.add(line);
repaint();
}
"how to draw graphics in JPanel out of paintComponent method?"
“如何通过paintComponent方法在JPanel中绘制图形?”
Don't. 别。 all custom painting should be done within the context of the
Graphics
object provided in the paintComponent
method. 所有自定义绘制都应在
paintComponent
方法中提供的Graphics
对象的上下文内完成。 So you need to anticipate what could possibly be drawn, and draw it. 因此,您需要预料可能会绘制的内容,然后进行绘制。 As seen above, this can be dynamic.
如上所述,这可以是动态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.