如何防止JButton改变大小?

时间:2014-01-20 07:54:16

标签: java swing jbutton layout-manager grid-layout

我正在尝试制作一个简单的游戏,你可以设置构成凯尔特人设计的瓷砖,而我似乎无法使按钮保持相同的尺寸。这是代码:

public class CTGContent {

    public static JPanel content = new JPanel();
    private static JButton board[][] = new JButton[20][20];

    static private Random random = new Random();

    public static int CTGcolumn = random.nextInt(14)+1;
    public static int CTGRow = 15;
    private static GridLayout boardLayout;

    public final int getBoardWidth(){
        return CTGcolumn*40;
    }

    public final int getBoardHeight(){
        return CTGRow*40;
    }

    public static void initializeBoard(){
        int row = 0;
        int column = 0;

        int defaultCOL = 0;
        int defaultROW = 0;

        boardLayout = new GridLayout(CTGRow, CTGcolumn);
        content.setLayout(boardLayout);

        Random determine = new Random(); 

        while (row < CTGRow){
            column = 0;
            while (column < CTGcolumn){
                board[row][column] = new JButton(new ImageIcon("images\\template.gif"));
                board[row][column].setPreferredSize(new Dimension(40, 40));
                board[row][column].setMaximumSize(new Dimension(40, 40));
                board[row][column].setMinimumSize(new Dimension(40, 40));
                content.add(board[row][column]);
                column++;
            }
            row++;
        }
    }

    private static void build(){

        initializeBoard();

        JFrame window = new JFrame("testing the menubar");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setContentPane(content);
        content.add(new JLabel("My Label"));
        window.pack();
        window.setVisible(true);    

    }

    public CTGContent() {

    }

    public CTGContent(JFrame window){

        initializeBoard();
        window.add(content);

    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater( new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                    build();
            }
        });
    }
}

它通常从正确的尺寸开始但是由于某种原因,如果我调整窗口大小或者用它改变大小的东西。无论怎样,我都需要它们保持相同的尺寸。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

变化:

window.setContentPane(content);

要:

JPanel contentCenter = new JPanel(new GridBagLayout());
contentCenter.add(content);
window.setContentPane(contentCenter);

enter image description here

enter image description here

还有其他方法可以做到这一点,例如将布局设为FlowLayout,但GBL会使其保持良好的居中 - 垂直和水平。

提示

  1. 请了解课程,方法和方法的常见Java naming conventions(特别是用于名称的情况)属性名称&amp;一贯地使用它们。
  2. 为了更好地提供帮助,请发布MCVE。该代码只需要导入才能使其成为MCVE。
  3. 另请参阅this answerCentering a JLabel on a JPanel

答案 1 :(得分:0)

您使用GridLayout因为您的按钮水平/垂直调整大小总是填充整个网格单元格。为了防止您使用其他LayoutManager,例如GridBagLayout

请务必阅读setting size to components