In: Computer Science
Create a simple Swing application that animates a square diagonally across its window once. You may set the size of the window and assume that it doesn’t change. Using Java swing using timers
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// MovingSquare.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class MovingSquare extends JFrame {
//declaring important attributes
private int x, y; //current position of square
private int size; //size of square
private Color color; //square color
private Timer timer; //timer for running animation
public MovingSquare() {
//will exit on close button click
setDefaultCloseOperation(EXIT_ON_CLOSE);
//using 500x500 size
setSize(500, 500);
//assigning values to instance variables
x = 0;
y = 0;
size = 80;
color = Color.BLUE;
//initializing a timer that runs every 50 ms
timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//updating x and y values by 5
x+=5;
y+=5;
//if the square goes out of bounds, stopping the timer
if ((x + size) >= getWidth() || (y + size) >= getHeight()) {
timer.stop();
}
//repainting to make things visible
repaint();
}
});
//starting timer
timer.start();
//making window visible
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
//using the specified color
g.setColor(color);
//drawing a filled square
g.fillRect(x, y, size, size);
}
public static void main(String[] args) {
//initializing GUI
new MovingSquare();
}
}
/*OUTPUT*/