This is a part of my code which does some sort of animation; however, there seems to be something wrong: Whenever I try to use the passed ‘g’ from inside the anonymous class to draw anything, it does nothing, yet when I used it outside the anonymous class (inside the rollBalls method) it does what it’s supposed to do. Any idea why? And how do I fix this? Thank you.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
rollBalls(g);
}
private void rollBalls(final Graphics g) { //Roll all 3 balls on the bar
new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
}).start();
}
Your problem is several fold but first and foremost you understand that the Graphics object passed into a paint or paintComponent method usually does not persist and may be disposed of after the method completes. Next you have program logic being called from within a paintComponent method which should never be done. You do not have full control of when or even if the paint or paintComponent methods are called and thus should not have it dictating your app’s logic.
For this reason you do not do Swing graphics in this way. Instead, have your timer outside of any paintComponent method, have it update class fields, have it then call repaint() and have your paintComponent use these class fields to do drawing as needed and this time with a stable Graphics object that is passed into it via its parameters.
I understand that your code is “just a sample”, but your doing things wrong by trying to paint directly from within actionPerformed. You simply shouldn’t do this.