I'm currently creating a connect four game for fun and was just about finished when I decided that it would be cool to add a falling animation. I know of a couple different ways to do this, but I'm not sure what would be 'best'.
Since my GUI is made up of JComponents I figured I should use javax.swing.Timer
for Thread safety.
ActionListener update = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
};
};
Timer timer = new Timer(10, update);
timer.start();
My real question is what should I do to update my game board?
Would it be better to call repaint()
(maybe even repaint(Rectangle rec)
)and handle everything in paint()
or create another class for a connect four piece and add that Component to my GUI.
The other class for my connect four piece is currently this...
public class Piece extends JLabel{
private Color color;
private Ellipse2D circle;
public Piece(Color color, int radius) {
this.color = color;
circle = new Ellipse2D.Float(0, 0, radius, radius);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g2);
g2.setColor(color);
g2.fill(circle);
}
}
If I add the component to the GUI, I would have to call invalidate()
and validate()
quite often since the timer I have currently is fast, and I'm not sure if that's better or worse than calling repaint()
.
I've tried both of these ways, and both seem to work fine, I'm just not sure which is more efficient? I'd rather not have it be more taxing that it needs to be - for learning purposes.
Also if there's a better way than what I've thought of please let me know. I'm open to all suggestions
Your Piece is a component. All you have to do is call setLocation(...) and the component will repaint itself automatically. No need for any custom painting.
If I add the component to the GUI, I would have to call invalidate() and validate()
Just set the layout to null. You will need to set the size of the component, but no need to call invalidate() or validate() since those methods are used by a layout manager.