Java 获取向容器添加窗口时出错

Java 获取向容器添加窗口时出错,java,swing,jframe,Java,Swing,Jframe,我正在尝试创建一个JavaSwing应用程序,它可以在单击按钮时显示一个表。我收到“将窗口添加到容器”错误。我知道我可能应该尝试添加一个JPanel而不是JFrame,但我的努力不起作用。任何帮助都将不胜感激。下面是代码 import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable;

我正在尝试创建一个JavaSwing应用程序,它可以在单击按钮时显示一个表。我收到“将窗口添加到容器”错误。我知道我可能应该尝试添加一个JPanel而不是JFrame,但我的努力不起作用。任何帮助都将不胜感激。下面是代码

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Courtney
 * javax.swing.JFrame
 */
public class TablePractice extends javax.swing.JFrame {

    /**
     * Creates new form TablePractice
     */
    public TablePractice() {
        initComponents();
        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Get Table");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(311, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jButton1)
                .addContainerGap(258, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


         //Create and set up the window.
        //JPanel panel = new JPanel();
        JFrame frame = new JFrame("TablePractice");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        TablePractice newContentPane = new TablePractice();
        //newContentPane.setOpaque(true); //content panes must be opaque
        frame.getContentPane().add(newContentPane);
        //frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TablePractice().setVisible(true);


            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}
导入java.awt.Dimension;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.JScrollPane;
导入javax.swing.JTable;
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
/**
*
*@作者考特尼
*javax.swing.JFrame
*/
公共类TablePractice扩展了javax.swing.JFrame{
/**
*创建新的表格练习
*/
公共实践(){
初始化组件();
String[]columnNames={“名字”,
“姓氏”,
“运动”,
“#年”,
“素食者”};
对象[][]数据={
{“凯西”,“史密斯”,
“滑雪板”,新整数(5),新布尔值(假)},
{“约翰”,“多伊”,
“划船”,新整数(3),新布尔值(真)},
{“苏”,“黑”,
“编织”,新整数(2),新布尔值(假)},
{“简”、“白”,
“快速读取”,新整数(20),新布尔值(真)},
{“乔”,“布朗”,
“Pool”、新整数(10)、新布尔值(false)}
};
最终JTable表=新JTable(数据、列名称);
表.setPreferredScrollableViewportSize(新维度(500,70));
表.setFillsViewPerthweight(真);
//创建滚动窗格并将表添加到其中。
JScrollPane scrollPane=新的JScrollPane(表);
//将滚动窗格添加到此面板。
添加(滚动窗格);
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jButton1=newjavax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText(“Get Table”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addContainerGap(311,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19,19,19)
.addComponent(jButton1)
.addContainerGap(258,简称最大值))
);
包装();
}//                         
私有void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
//创建并设置窗口。
//JPanel面板=新的JPanel();
JFrame=新JFrame(“表格练习”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建并设置内容窗格。
TablePractice newContentPane=新建TablePractice();
//newContentPane.setOkable(true);//内容窗格必须是不透明的
frame.getContentPane().add(newContentPane);
//frame.setContentPane(newContentPane);
//显示窗口。
frame.pack();
frame.setVisible(true);
}                                        
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(TablePractice.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
公开募捐{
新建TablePractice().setVisible(true);
}
});
}
//变量声明-不修改
私有javax.swing.JButton jButton1;
//变量结束声明
}
<