user3578318
user3578318

Reputation: 65

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 :

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

Answers (1)

Paul Samsotha
Paul Samsotha

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

Related Questions