简体   繁体   中英

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?

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM