Reputation: 65
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 :
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 ?
Upvotes: 2
Views: 1687
Reputation: 209132
"any suggessions please ?"
Keep a list of Line2D
objects in the Panel
class. (List<Line2D>
)
Iterate through the list in the paintComponent
method
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
public void addLine(Line2D line) {
lines.add(line);
repaint();
}
"how to draw graphics in JPanel out of paintComponent method?"
Don't. all custom painting should be done within the context of the Graphics
object provided in the paintComponent
method. So you need to anticipate what could possibly be drawn, and draw it. As seen above, this can be dynamic.
Upvotes: 2