Search code examples
javaalignmentjpaneljlabelflowlayout

JPanel flipping out, FlowLayout not working as intended


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?


Solution

  • 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.