Search code examples
javaswingjframejbutton

JButtons incorrect size


I want to draw a 13x13 tiles board using JFrame. Here's the code:

public static void drawBoard() {
    final int TILE_SIZE = 60;
    final int TILES = 13;
    JFrame jFrame = new JFrame("Board");
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setSize(TILE_SIZE * TILES + 17, TILE_SIZE * TILES);
    jFrame.setResizable(false);
    JButton button = null;
    ImageIcon icon = null;
    for (int y = 0; y < TILES; y++) {
        for (int x = 0; x < TILES; x++) {
            button = new JButton(alphabet[x] + "" + alphabet[y]);
            button.setName(alphabet[x] + "" + alphabet[y]);
            button.setBounds(TILE_SIZE * y, TILE_SIZE * x, TILE_SIZE, TILE_SIZE);
            button.addActionListener(new Clicked());
            button.setBackground(Color.WHITE);
            jFrame.getContentPane().add(button);
        }
    }
    jFrame.setVisible(true);
}//end drawBoard

Now, when I run the code, it shows me a grid of buttons, but the one at the bottom right corner is the same size of the frame.


Solution

  • but the one at the bottom right corner is the same size of the frame.

    Swing was designed to be used with layout managers. The layout manager will determine the size/location of a component based on the rules of the layout manager.

    In the case of a JFrame, the default layout manager is the BorderLayout. When you add a component to the BorderLayout without using a "constraint" the component is added to the CENTER. However only one component can be added to the CENTER. So only the last component added is give a size/location by the layout manager. In this case the rule is to make the button the size of the space available in the frame.

    If you want to have a grid, then you should be using a GridLayout. Then the layout manager will make each button the same size.

    Read the section from the Swing tutorial on Layout Managers for more information. There are working examples for both the BorderLayout and the GridLayout.