0

I am trying to draw graphics by calling the class Habitat in the code below. I am calling it from a loop. I am guessing this isn't the best way to do it as is it making multiple instances of the same name? Sorry, new to Java so hope this makes sense.

public Habitat (int c,int w,int h,int[][] s) {
    habitatWidth = w;
    habitatHeight = h;
    plantSize = s;
    counter = c;
    p1 = new Plants(10,10,40,s);
}

public void paintComponent (Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                                           RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHints(rh);

    //sets background color
    Rectangle2D.Double r = new Rectangle2D.Double(0, 0, habitatWidth, habitatHeight);
    g2d.setColor(new Color(0, 0, 0));

    // fill the shape
    g2d.fill(r);

    //draw the plant p1
    p1.drawPlants(g2d);
}
Abra
  • 19,142
  • 7
  • 29
  • 41
Peterlem
  • 1
  • 1
  • 4
    You don't call the `paintComponent` method at all. You call `repaint`, which calls the `paintComponent` method. Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) section. – Gilbert Le Blanc Oct 26 '22 at 19:38
  • 3
    Don't call repaint() from a loop. If you need animation, you should be using a Swing Timer. For example: https://stackoverflow.com/a/54028681/131872 – camickr Oct 26 '22 at 20:16
  • For checking the code, always add `@Override` before overriding _and implementing_ methods. – Joop Eggen Oct 27 '22 at 11:26

0 Answers0