I need to create a 4 x 4 grid of rectangles in Java, I then need these rectangles to change color in a sequence.
I've never done any graphical work before, just things in the console.
I started by doing some research and created a 650 x 650 JFrame
to put the rectangles in.
After that I used GridLayout
and managed to create a 4 x 4 grid out of buttons using window.JButton
which wasn't right.
How would I create rectangles instead? And would it be right to use for loops with ++ to time the animation?
I couldn't find anything that worked for my needs when searching on stackoverflow and google. Sorry if this is a stupid question. I'm new to this and I'm doing for an apprecticeship.
Here's how I would like it to look like, with each rectangle changing color in a time interval
You could use jLabel, and set background color to it. How you do it, you can read here: How do I set a JLabel's background color?
Then just use for loop and Thred.sleep to change there color in animation.
From @Eng.Fouad answer (so give him credit and upvote his answer too), I made some changes, this example shows how to use a Swing Timer which changes color every second from green to red. I'm using a simple
JLabel
for demonstration purposes, take this logic into theGridLayout
you have:Here are some screen shots on how it looks: