设置JButton的宽度和高度

时间:2015-09-06 01:57:43

标签: java swing resize jbutton

我正在尝试创建一个填满整个屏幕的JButtons方格。

我如何设置JButton的尺寸?如果按钮确实改变了尺寸并且我调整了窗口的大小,则按钮会变回最小尺寸。我尝试使用setSize和setBounds。

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Random;

public class GridButton extends JPanel{

    static int gridL;
    int level = 1;

    JButton[] field;

    public GridButton() {}

    public GridButton(int gridL) {
        field = new JButton[(int) Math.pow(gridL, 2)];
        GridButton.gridL = gridL;

        JFrame f = new JFrame("Game");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel main = new JPanel(new GridBagLayout());
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        f.setSize(1080, 1030);
        f.setVisible(true);

        main.setSize(1079, 1029);
        main.setVisible(true);

        SaveReader sr = new SaveReader();
        level = sr.returnLevel();

        int squareL = (int) Math.floor(970/gridL)-1;
        int times = 0;

        for(int j=0; j<gridL; j++) {
            for(int i=0; i<gridL; i++) {
                field[times] = new JButton();
                c.gridx = i;
                c.gridy = j;
                c.gridheight = 1;
                c.gridwidth = 1;
                c.weightx = 1/gridL;
                c.weighty = 1/gridL;
                field[times].setBounds((20+squareL*j), (20+squareL*i), squareL, squareL);

                main.add(field[times], c);
                times++;
                System.out.println(times);
            }
        }

        f.add(main);
    }

    public static void main(String[] args) {
        new GridButton(5);
    }

}

0 个答案:

没有答案