简体   繁体   English

Java-JLabel组件仅在调整大小时显示

[英]Java - JLabel components only show when resizing

When I run my code the JFrame Window shows the smallest possible version of the title frame, it needs to be resized in order to actually show anything. 当我运行代码时,JFrame窗口会显示标题框架的最小版本,需要调整其大小才能实际显示任何内容。 Usually this is due to the lack of a pack() or setVisible(true) at the end, but not in this case. 通常这是由于末尾缺少pack()或setVisible(true)引起的,但在这种情况下并非如此。 This is the code: 这是代码:

public static void main(String[] args) throws FileNotFoundException {
    Boolean[][] maze = Exercise4.readMaze();
    int row = maze.length;

    JFrame f = new JFrame("Maze");
    f.setLayout(new GridLayout(row, row));

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < row; j++) {
            JLabel grid = new JLabel();
            grid.setOpaque(true);
            if (maze[i][j].equals(false))
                grid.setBackground(Color.black);
            else grid.setBackground(Color.white);
            f.add(grid);
        }
    }
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
}

JLabel grid = new JLabel(); is creating a blank label, it's default size will 0x0 , so when you pack the frame, it's been packed down to preferred size of, essentially 0x0 正在创建空白标签,默认大小为0x0 ,因此pack框架时,将其打包为首选大小,基本上为0x0

Consider using something like JLabel grid = new JLabel(" "); 考虑使用类似JLabel grid = new JLabel(" "); to start with, but I might consider using a "blank" icon of a specified size instead 首先,但我可能会考虑使用指定大小的“空白”图标代替

You could also use some text and set the foreground (text) color to the same color as the background, but I'd personally use a transparent icon, but that's me 您也可以使用一些文本并将foreground (文本)的颜色设置为与背景相同的颜色,但是我个人使用透明图标,但这就是我

尝试创建一个JPanel并将所有组件放入其中,然后将JPanel添加到JFrame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM