1

I am trying to utilize the Graphics object for my method, but it returns an error. It is due to the fact that I can't use g.fillOval in the actionPerformed method, but I must use it there or else my code won't work.

Class Code:

public class CityPanel extends JPanel implements ActionListener{

    int[] sunPos = {};
    int[] x = {50,100, 150, 200, 250, 300, 350, 400, 450};
    int[] y = {200, 150, 100, 50, 25, 50, 100, 150, 200};
    int tracker = 0;

    //more defined variables here

    public CityPanel(Color c) {
        //code in here
    }

    public void paintComponent(Graphics g){
        Graphics2D ga = (Graphics2D)g;
        super.paintComponent(g);
        g.drawLine(0,300,500,300);
    }

    public void actionPerformed(ActionEvent e){ // what happens
        if (e.getSource() == time) {
            g.fillOval(x[tracker],y[tracker], 50, 50); //error here
            super.repaint();
        }
    }

}

Angelina Tsuboi
  • 196
  • 1
  • 2
  • 14
  • 3
    Set a variable in the `actionPerformed` and check that variable in `paintComponent` to determine whether to draw an oval. It's a good idea to keep all your painting within `paint` methods that get passed a `Graphics` object as appropriate. – khelwood Jun 17 '20 at 13:52
  • I did that, but I only want the oval to be drawn once at a time. – Angelina Tsuboi Jun 17 '20 at 13:56
  • 1
    All custom painting needs to be done in the paintComponent() method. You need to set properties in your CityPanel to determine what is painted. If you want to dynamically add an oval to be painted, then your class needs to have an ArrayList of Ovals to be painted. The paintComponent() method will iterate through the ArrayList and paint each Oval. You then have a method like `addOval(…)` to add an oval to be painted to the ArrayList. See the `DrawOnComponent]` example from [Custom Painting Approaches](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for a working example. – camickr Jun 17 '20 at 14:02
  • You mean something [like this](https://stackoverflow.com/questions/42158156/drawing-shapes-on-a-jform-java/42167399#42167399)? Instead of painting in the `ActionPerformed` send a Shape to the `paintComponent(...)` method from the `ActionPerformed` – Frakcool Jun 17 '20 at 20:32

0 Answers0