There are multiple possible ways to solve this, but one easy one is to give a JPanel a GridLayout, and then fill it with JLabels with ImageIcons that show empty circles. When the column is selected, the appropriate JLabel is given a new ImageIcon via setIcon
that shows a color filled circle.
Also,
- Always strive to separate your program logic code from your GUI code, since the better your separation, the easier will be your ability to debug and enhance.
- Work on small problems one at a time. Don't move on to the next problem until the current small step is solved.
- Work out your logic and ideas on paper first before committing it to code.
- Don't "work with paint". If you need to do Swing graphics, you'll want to override a JPanel or JComponent's
paintComponent
method. The paint method also concerns itself with drawing borders and children, and so overriding it can have nasty and unexpected side effects on these. Also paint is not double buffered by default, and this can lead to bad animation once you start working with animation.
Edit
You state in comment:
Will it be okay to use JButton though? Because that was what i used during my first attempt. I can use setIcon with it too right?
Do you mean use a JButton instead of a JLabel? That would work, and yes you can call setIcon
on JButtons, but would make all your rectangles look like buttons. So if that's OK, then do it. Otherwise, you could still use JLabels, and then create a row grid of JButtons to put below or above your game grid, and then have the user press those buttons, and in their ActionListeners have them change the icons of a JLabel in the selected column.
But having said this, I mainly recommend that you use what works best for you. The learning will be in the creating, no matter what you create.
Edit 2
You ask:
do you think it'll be possible/a nice approach to store jlabels in an array and then lay them out in a panel?
Absolutely, either an array of JLabel[]
or a List<JLabel>
I think is not only possible but in fact essential for this to work well. I think that you're definitely on the right track here.