arjacsoh
arjacsoh

Reputation: 9232

Java Swing JPanel. How do I paint shapes?

I have implemented a class DrawingPane extends JPanel to draw some shapes. I have created inside an individual method for each type of shape, for example to circles corresponds :

public void paintCircles(Graphics g) {
           super.paint(g);

However I am not able to invoke this from another class through a reference to class DrawingPane. How can this be done? If it is not possible this way, how can I invoke an individual method to draw each type of shape, since the code requirements are different with different shapes?

Moreover, the method scrollRectToVisible from class JPanel does not apply to objects RoundRectangle2D.Double. How can make these shapes also visible?

Upvotes: 0

Views: 2885

Answers (2)

Jonas
Jonas

Reputation: 128827

You need to implement paintComponent(Graphics g) in your DrawingPane and you can use draw(Shape s) to draw any shape:

public void paintComponent(Graphics g) {
        super.paintComponent(g); 
        Graphics2D g2 = (Graphics2D)g;    
        g2.draw(yourShape);
}

Upvotes: 3

StanislavL
StanislavL

Reputation: 57381

You can cast your Graphics to Graphics2D and use public void draw(Shape s) method passing all the Shapes you have. For any Shape you can use public Rectangle getBounds() and pass the Rectangle to the scrollRectToVisible.

Upvotes: 2

Related Questions