That seems correct at a glance (though I also do not work with graphics frequently).
Note that if you were to release the key your ovals may disappear from the screen at the next redraw.
You can create a simple Oval
wrapper class to store details like the x, y, width, and height, and put those Oval
s into a list that is an instance variable of your KeyListenerDemo
.
Your if-blocks would be something akin to:
else if(keyCode == KeyEvent.VK_Z)
{
Oval o = new Oval(x + radius, y + radius, 2 * radius, 2 * radius);
ovals.add(o); // where ovals is an ArrayList<Oval> or LinkedList<Oval>
g.fillOval(o.x, o.y, o.width, o.height);
}
At the public void paint(Graphics g)
method you'd loop through the list and (re)draw those ovals.
Edit: I'd implement the oval class like:
public class Oval {
int x;
int y;
int width;
int height;
public Oval(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
The list is simply declared as protected List<Oval> ovals = new LinkedList<>();
, right above your main method. To loop over it (in your paint method, where g
is available, you can use:
for(Oval o : ovals){
g.fillOval(o.x, o.y, o.width, o.height);
}
Hopefully this helps!