I found some code that does something that interests me, but I don't fully understand the implementation. The part I am struggling with is where the author "overrides" an "actionPerformed" method.
I have a vague idea of why someone would want to override a method that is inherited from the superclass, but I haven't needed to override any inherited method thus far in my career, so I am a bit lost. That is compounded by my lack of experience with "ActionListener".
So, if someone would be so kind as to explain to me "why" the author needed to "override" the "actionPerformed" and what this override actually does for this code, I would really appreciate it.
Here is the code...
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
public class SimpleShape extends Thread implements Runnable {
public static void main(String[] args) {
SimpleShape ss = new SimpleShape();
}
private int ya = 50, xa = 50;
private PaintSurface paintSurface = new PaintSurface();
private Timer swingTimer = new Timer(20, new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
xa++;
if (xa > paintSurface.getSize().width) {
xa = 0;
}
paintSurface.repaint();
}
});
public SimpleShape() {
JFrame j = new JFrame();
j.setSize(300, 300);
j.setLocation(200, 200);
j.setTitle("simple shape program");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.add(paintSurface);
j.setVisible(true);
swingTimer.start();
}
private class PaintSurface extends JComponent {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = new Ellipse2D.Float(xa, ya, 50, 50); // x usually comes first here, not y
g2.setPaint(Color.GREEN);
g2.draw(s);
}
}
}