Hi all, I've got a very crude Swing GUI with 6 JLabel's sitting on a JPanel using a GridLayout. It's for a card game, and the 6 JLabel's are actually displaying my playing cards. (they are displayed as an ImageIcon within the JLabel)
Anyway, I've set up a MouseListener interface so that when a user clicks one of the JLabel's, it will execute some code. Everything seemed to be working great until I noticed that if you click in between the JLabel's, it will register as though you actually clicked ON the JLabel immediately to the left. I've tried adjusting the size of my JLabel's using something like lbl1.setSize(25,20); but it seems to do nothing. I can't figure why the heck it's doing this, but more importantly I can't seem to fix it.
Any help or suggestions would be greatly appreciated!
Joined: Mar 08, 2003
Ok, I knew as soon as I posted the question I'd figure it out. Turns out that when I was creating my GridLayout upon which the JLabels sit, I was passing in a zero for the "hgap" (horizontal gap) which probably meant that my JLablel's were butting up against each other. (even though the card images were not, still not sure why this is) I put a gap of 50 in there and now it seems to work fine.
The answer to the riddle lies in the GridLayout api. GridLayout will increase the size of its container's child component to fill each grid cell. Thus each JLabel expands to fill it's grid cell. You can verify this for yourself by adding a MouseMotionListener to the JLabels and showing the x,y position of the mouse in a JLabel or in the console. A solution to this is to add each JLabel to a JPanel and add the JPanel to the container that has the GridLayout. The JPanels will expand to fill the space inside each grid cell allowing the JLabel to remain at it's preferred size. You can verify this with the MouseMotionListener.
One difficulty that you may run into with this approach comes when the JLabel sizes are much smaller than the grid cells. In this case the JLabels will appear toward the top of the grid cell which is the behavior of the default FlowLayout of the JPanel to which you added the JLabel. To center the JLabel inside the grid cell you can use a GridBagLayout with default GridBagConstraints for each JPanel. A single instance of each should serve you well.