【问题标题】:Java Swing layout not appearingJava Swing 布局未出现
【发布时间】:2016-07-18 15:33:55
【问题描述】:

我刚刚开始使用 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() 中,但它会导致无限量的窗口打开,我每次都必须结束程序。

【问题讨论】:

    标签: java swing jframe


    【解决方案1】:

    您正在创建两个独立的JFrames:一个是您的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);
    }  
    

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2019-04-04
      • 2018-05-03
      • 2014-12-20
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多