gpt4 book ai didi

Java Swing 布局未出现

转载 作者:行者123 更新时间:2023-12-02 03:28:30 24 4
gpt4 key购买 nike

我刚刚开始用 Java 创建 GUI,通过这个基本设置,我无法在 JFrame 中显示任何内容:

public class Main extends JFrame {

public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main init = new Main();
}

public Main() {
Container pane = getContentPane();
pane.setBackground(Color.BLUE);
pane.setLayout(new FlowLayout());
JButton add = new JButton("Add");
JButton close = new JButton("Close");
JTextArea area = new JTextArea();
JScrollPane scroll = new JScrollPane(area);

add.setBounds(70, 125, 80, 20);
close.setBounds(70, 115, 80, 20);
pane.add(add);
pane.add(close);
pane.add(scroll);
AddClick added = new AddClick();
add.addActionListener(added);
}
}

我还尝试将所有 JFrame 内容移至 public Main() 中,但它导致无限量的窗口打开,每次我都必须结束程序。

最佳答案

您正在创建两个单独的 JFrame:一个是您的 Main 类,另一个是不相关的 JFrame。大多数自定义(包括添加组件)都发生在其构造函数中的 Main 中。但您只能将另一个 JFrame 设置为可见。

使用您的 Main 实例作为 JFrame 而不是创建另一个实例,问题将得到解决。

public static void main(String[] args) {
JFrame jframe = new Main(); //Use an instance of Main as your JFrame
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

关于Java Swing 布局未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com