Search code examples
javaswinggraphics2d

Graphics2D using constructor


I want to draw a straight line in JFrame using Line2D.Double, also I want do it with constructor (not through method). How I must declare variable g like in example on docs.oracle.com?

public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
...
}

Solution

  • Painting is always done in a method. In particular custom painting in Swing is done in the paintComponent() method of a Swing component like JComponent or JPanel.

    Read the Swing tutorial on Custom Painting for a better explanation and examples.