我一直在做这个项目的任务,但我一直被这个问题困扰。我是新手,不太了解编程术语,因此如果有人可以帮助解释为什么我的程序无法运行,那就太好了。
该程序的目的是在 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);
}
});
}
}
最佳答案
因为这看起来确实像家庭作业,我会给你一些指导,但不会给你代码。
将
Module5
的构造函数从 numbers 类移出到它自己的类中。还要从中删除void
返回类型,使其成为正确的构造函数。将 main 中的代码移至
Module5
的构造函数中。这是主框架,因此当您构建一个新框架时,应该在这里初始化它,而不是在 main 中。暂时删除setVisible
调用(这已在第 6 步中解决)完成 1 和 2 后,删除
frame
变量,您的Module5
是一个JFrame
,因此与frame
相关的任何内容都可以更改为关键字this
(表示此Module5
对象)还将
area
变量移至Numbers
类中 - 否则每个Number
本质上都会共享相同的文本区域,而这不是您想要的。不要将变量设置为
静态
,它们本不应该如此。完成这一切后,请确保它在事件调度线程上运行,方法是使您的主要方法像这样(我将给您的一段代码)
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Module5 mod5 = new Module5(); mod5.setVisible(true); } }); }
关于java - 如何显示具有多种布局的多个 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844136/