简体   繁体   English

如何从paintComponent方法中绘制JPanel中的图形?

[英]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.

相关问题 什么是JPanel / Graphics方法paintComponent? - What is the JPanel/Graphics method paintComponent? 如何在Swing中将DisplayJAI图像绘制到容器? 我想在PaintComponent方法中使用graphics2d将DisplayJAI绘制到Jpanel - How to draw DisplayJAI image to container in Swing? I want to draw DisplayJAI to Jpanel using graphics2d in PaintComponent method 在 JPanel 上绘制图形而不使用 PaintComponent 方法和重绘调用 - Painting Graphics on JPanel without using PaintComponent method and repaint call 如何使用图形在 JPanel 上绘图 - How to draw on a JPanel using Graphics 我已经调用paintComponent方法后如何在JPanel中绘制内容 - How do I draw something in a JPanel after I already called the paintComponent method paintComponent()方法未绘制到JPanel - paintComponent() method not drawing to JPanel 如何在paintComponent()方法之外访问Graphics对象 - how to access Graphics object outside paintComponent() method JApplet不使用paintComponent(Graphics g)方法绘制圆 - JApplet does not draw circle with paintComponent(Graphics g) method paintComponent 不在 JPanel 上绘制 - paintComponent doesn't draw on JPanel 为什么我的paintComponent方法覆盖我的JButton? 如何使JPanel上同时具有JButton和图形? - Why does my paintComponent method paint over my JButton? How can I make a JPanel have both a JButton and graphics on it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM