为什么我的JFrame是空的? [英] Why is my JFrame empty?

查看:66
本文介绍了为什么我的JFrame是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚为什么我的JFrame为空.我要去哪里错了?

I can't seem to figure out why my JFrame is empty. Where am I going wrong?

导入javax.swing.*;导入java.awt.FlowLayout;

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

公共类GUIExample扩展了JFrame {

public class GUIExample extends JFrame {

JCheckBox box1 = new JCheckBox("Satellite Radio");
JCheckBox box2 = new JCheckBox("Air Conditioning");
JCheckBox box3 = new JCheckBox("Manual Tranmission");
JCheckBox box4 = new JCheckBox("Leather Seats");
JRadioButton radio1 = new JRadioButton("Car");
JRadioButton radio2 = new JRadioButton("Pickup Truck");
JRadioButton radio3 = new JRadioButton("Minivan");
JTextField text = new JTextField();
ButtonGroup group = new ButtonGroup();

public void newGUI() {

    setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JPanel textPanel = new JPanel();

    add(textPanel);
    add(panel);

    panel.add(box1);
    panel.add(box2);
    panel.add(box3);
    panel.add(radio1);
    panel.add(radio2);
    panel.add(radio3);
    group.add(radio1);
    group.add(radio2);
    group.add(radio3);

}

public static void main(String[] args) {

    JFrame frame = new JFrame("GUI Example");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);

}

}

推荐答案

您忘记在jFrame中添加contentPane了,就像这样

You forgot to add the contentPane in your jFrame, something like this

frame.setContentPane(panel);

我注意到您正在使用继承来构建jFrame,因此在这种情况下,您需要实例化自己的类.我已经用最小的代码重构了您的代码以运行jFrame.

I notice you're using inheritance to build your jFrame, so in this case you need to instantiate your own class. I've refactored your code with the minimun to run an jFrame.

public class GUIExample extends JFrame {

    JCheckBox box1 = new JCheckBox("Satellite Radio");

    public static void main(String[] args) {
        JFrame frame = new GUIExample("GUI Example");
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        panel.add(box1);

        frame.setContentPane(panel);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}

基本上,您创建一个JFrame,创建一个JPanel,将组件添加到此面板,然后使用 setContentPane(panel)将面板设置为您的框架.

Basically you create an JFrame, create an JPanel, add your components to this panel and set the panel to your frame with setContentPane(panel).

对不起,我现在无法对此进行测试,因此,如果有人可以并根据需要进行修复,将不胜感激,但这是类似的事情.

I'm sorry I can't test this right now, so if someone could and fix if needed, would really appreciate, but is something like this.

这篇关于为什么我的JFrame是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆