Question

The other day this code was working. I changed some things and re-ran it and now it doesn't work as intended. Obviously something I changed altered the behaviour, but I have gone back and reverted all of those changes and it still doesn't work. Disregarding that bit of information (to start), why does this code not place a 15x15 grid of JLabels inside of a JPanel?

gameBoard.setLayout(new FlowLayout());

for (int i = 0; i < 15; i++)
{
    for (int j = 0; j < 15; j++)
    {
        JLabel tile = new JLabel("");                       
     tile.setHorizontalAlignment(SwingConstants.CENTER);
        tile.setPreferredSize(new Dimension(27, 27));
        tile.setBorder(new EtchedBorder());
        tile.setEnabled(false);

        gameBoard.add(tile);
    }
}

gameBoard is a JPanel defined through NetBeans' GUI Builder. It has a preferred size, a maximum size (same as preferred). The horizontal/vertical resizable options are disabled, yet when this code runs every button extends horizontally in a row without ever breaking.

If I understand correctly, FlowLayout is supposed to wrap elements when they reach the end of their containing element. This was happening before today, I don't really know why this behaviour stopped?

Was it helpful?

Solution 4

I figured it out. Apparently I had to set the preferredSize within the code itself. Just setting it in the Netbeans properties window is not enough. Strange.

OTHER TIPS

It would be much better to use a GridLayout.

GridLayout gridLayout = new GridLayout(15, 15);

The flow layout may have changed due to using a new look and feel, different fonts or some Java VM upgrade. Defining a flow layout for this use is not recommended as you're reliant on underlying sizes that can vary across virtual machines or look and feels.

In the interests of teaching a man how to fish:

Revision control systems are great. Even your system is making a back up of your source at frequent intervals.

A useful debugging technique is to take away things until it does work. Does setting a border cause you code to break. Going the other way, can you write a trivial program that demonstrates the problem.

I've found great success and control using TableLayout and I would recommend it to anyone. You can define the columns and rows using specific number of pixels, or you can just use TableLayout.PREFERRED for each column and/or row. Very nice and flexible Layout. We use it everywhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top