我试图制作一个17 x 17的GridLayout板,但是当我运行代码时,我生成的板被弄乱了,看起来像这样,而不是17 x 17的按钮板:

java - 按钮未完全加载到GridLayout中-LMLPHP

所以我的问题是,为什么显示板像这样奇怪,如何使它显示我想要的17 x 17按钮板?

这是我正在使用的代码:

public class TheJFrame {
public static final char[][] board = new char[17][17];
public static class TheJFramez {
    JFrame boardz = new JFrame("Game of Life");
    JPanel panel = new JPanel();
    public TheJFramez(){
        int r = 0,c;
        boardz.setLayout(new GridLayout(board.length,board[r].length,1,1));
        for(r=0;r<board.length;r++){
            for(c = 0;c<board[r].length;c++){
                JButton tats = new JButton(" " + board[r][c] + " ");
                panel.add(tats);

            }
        }
        boardz.add(panel);
        boardz.setVisible(true);
        boardz.setSize(1200, 700);
        boardz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}
public static void main(String[] args) {
    new TheJFramez();
}
}

最佳答案

在这段代码中,当您将按钮添加到未指定布局的“面板”中时,已将“ boardz”的布局设置为GridLayout,因此,它采用默认布局,当您将面板添加到“ boardz”时,该面板将以网格布局进行排列,而“面板”的组件仍将使用默认布局。

因此,您想将JButton添加到boardz,并且不使用面板。

这是正确的代码:

import java.awt.*;
import javax.swing.*;
public class TheJFrame {
public static final char[][] board = new char[17][17];
public static class TheJFramez {
    JFrame boardz = new JFrame("Game of Life");
    JPanel panel = new JPanel();
    public TheJFramez(){
        int r = 0,c;
        boardz.setLayout(new GridLayout(board.length,board[r].length));
        for(r=0;r<17;r++){
            for(c = 0;c<17;c++){
                JButton tats = new JButton(" " + board[r][c] + " ");
                boardz.add(tats);
                System.out.print(board[r][c]);
            }
            System.out.println();
        }

        boardz.setVisible(true);
        boardz.setSize(1200, 700);
        boardz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}
public static void main(String[] args) {
    new TheJFramez();
}
}


java - 按钮未完全加载到GridLayout中-LMLPHP

关于java - 按钮未完全加载到GridLayout中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36820508/

10-12 00:25
查看更多