JButtons 没有出现在 GridBagLayout 中

JButtons not appearing in GridBagLayout

我正在尝试创建一个 10 x 10 的正方形 JButton 网格,中间没有间距。我相信,为了实现这一点,我唯一的解决方案是 GridBagLayout。但是,我停留在第一步 - 当我使用循环时我无法让它们出现。这是我的。

Class 使用 main() 函数:

public class PixelArtist {
    public static void main(String[] args) {
        try {
            PixelArtistGUI frame = new PixelArtistGUI();
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

GUI 处理程序 class:

public class PixelArtistGUI extends JFrame {
    public PixelArtistGUI() {
        setTitle("PixelArtist");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        JPanel contentPane = new JPanel(new GridBagLayout());
        this.add(contentPane);
        contentPane.setSize(500, 500);
        GridBagConstraints c = new GridBagConstraints();

        JButton b;

        for (int j = 0; j < 10; j++) {
            for (int i = 0; i < 10; i++) {
                b = new JButton();
                c.gridx = i;
                c.gridy = j;
                contentPane.add(b,c);
            }
        }

    }
}

上面所做的只是打开一个非常小的、看似空的 JFrame,如下所示:

我做的最后一件事是添加了 contentPane.setSize(500, 500); 行,但这似乎没有任何区别。

我相信这很简单 - 在此先感谢您的帮助。

你至少应该使用

public void add(Component comp,Object constraints)

即:

contentPane.add(b,c);

正如 FredK 所说,将 contentPane 添加到框架中

这应该能显示一些东西(我测试过)。检查我添加语句的行 // <<<<<<

  • 将面板设置为内容面板
  • 设置内容窗格的首选大小
  • 正在调用 pack 以将框架调整为首选大小
  • 使用 SwingUtilities.invokeLater 显示帧以配合事件调度线程

import java.awt.*;
import javax.swing.*;

public class PixelArtistGUI extends JFrame {
    public PixelArtistGUI() {
        setTitle("PixelArtist");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        JPanel contentPane = new JPanel(new GridBagLayout());
        setContentPane(contentPane); // <<<<<
        contentPane.setPreferredSize(new Dimension(500, 500)); // <<<<<
        GridBagConstraints c = new GridBagConstraints();

        JButton b;

        for (int j = 0; j < 10; j++) {
            for (int i = 0; i < 10; i++) {
                b = new JButton();
                c.gridx = i;
                c.gridy = j;
                contentPane.add(b,c);
            }
        }
        pack(); // <<<
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() { // <<<
            @Override
            public void run() {
                try {
                    new PixelArtistGUI().setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}