如何显示具有多个布局的多个 JPanel?

How do I display multiple JPanels with multiple layouts?

我一直在做这个项目的任务,但一直被这个问题困扰。我是新手,不太了解编程术语,所以如果有人可以帮助解释为什么我的程序无法运行,那就太好了。

该程序的目的是在 10x10 布局中显示随机生成的 1 和 0 矩阵,并在顶部放置一些具有功能的按钮。我只知道如何显示所有内容。

提前致谢。

更新:: 告知提供我所有的代码会有帮助

public class Module5 extends JFrame {

private static JTextArea area = new JTextArea();
private static JFrame frame = new JFrame();
private static JPanel general = new JPanel();
private static JPanel buttons = new JPanel();
private static JPanel numbers = new JPanel();
private static JButton button0 = new JButton("Reset to 0");
private static JButton button1 = new JButton("Resset to 1");
private static JButton buttonReset = new JButton("Reset");
private static JButton quit = new JButton("Quit");

public static class Numbers extends JPanel {

    public Numbers() {
        area.setText(Integer.toString((int) Math.round(Math.random())));
        this.add(area);
    }    

    public void Module5(){

        numbers.setLayout(new GridLayout(10, 10));
        for (int i = 0; i < 100; i++) {
            this.add(new Numbers());
        }
    }
}

public static void main (String[] args) {

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);

    general.setLayout(new BoxLayout(general, BoxLayout.Y_AXIS));
    general.add(buttons);
    general.add(numbers);

    buttons.add(button0);
    buttons.add(button1);
    buttons.add(buttonReset);

    buttons.add(quit);
    quit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    });
}

}

因为这看起来确实像作业,所以我会给你一些指导,但不会给你代码。

  1. Module5 的构造函数从数字 class 移到它自己的 class 中。还要从中删除 void return 类型,使其成为正确的构造函数。

  2. 将 main 中的代码移动到 Module5 的构造函数中。这是主框架,所以当你构建一个新框架时,它应该在这里初始化,而不是在主框架中。并暂时删除 setVisible 调用(这在编号 6 中解决)

  3. 完成 1 和 2 后,去掉你的 frame 变量,你的 Module5 是一个 JFrame 所以与 frame 有任何关系可以只更改为关键字 this(表示此 Module5 对象)

  4. 同时将 area 变量移动到 Numbers class 内 - 否则每个 Number 本质上将共享相同的文本区域这不是你想要的。

  5. 没有你的变量,因为 static 它们不需要。

  6. 一旦这一切都完成了,通过像这样制作你的主要方法(我会给你的一段代码)确保它在事件调度线程上运行

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                Module5 mod5 = new Module5();
                mod5.setVisible(true);
            }
        });
    }