Java UI - 不创建和填充表

时间:2016-09-09 17:02:52

标签: java mysql swing jtable

我正在尝试从mysql数据库中的表中提取数据,并将结果填充到JTable中。 UI中目前有3个选项卡,前两个是输入屏幕,工作正常。第三个选项卡,我试图运行一个查询(按下按钮后)并在JTable中显示结果。我没有收到错误消息,但屏幕不显示表格。以下是我的代码。任何帮助将不胜感激。注意,用户名和密码已被泛型替换。查询也已简化,直到我可以使它工作。 system.out.print只是检查它是否正在提取任何数据。

  private void salePropertyActionPerformed(java.awt.event.ActionEvent evt) {                                             
     String sSelectQuery = "";
    Statement statement=null;
    Connection conn = null;
    //PreparedStatement pStatement =null;
    JPanel panel= spPanel;

    TableColumn column;
    JTable spTable = jTable1;
    Vector columnNames = new Vector();
    Vector data = new Vector();
    spTable = new JTable(data,columnNames);
    JScrollPane scrollPane = new JScrollPane(spTable);
    panel.add(scrollPane);

    try {
        String myDriver = "com.mysql.jdbc.Driver";
        String myURL = "jdbc:mysql://localhost:3306/realestate?autoReconnect=true&useSSL=false";
        Class.forName(myDriver);
        conn=DriverManager.getConnection(myURL,"root","jul1664bd");

    /*Storing SQL statement*/
    sSelectQuery ="SELECT propertyID, propertyPrice FROM property";


    statement = conn.createStatement();
        try (ResultSet rs = statement.executeQuery(sSelectQuery) //executes the query
        ) {
            ResultSetMetaData metaData = rs.getMetaData();
            int columns = metaData.getColumnCount();
            for(int i = 1; i<=columns; i++){
                columnNames.addElement(metaData.getColumnName(i));
            }

            while (rs.next()){
                Vector row = new Vector(columns);
                for (int i=1; i<=columns; i++){
                    row.addElement(rs.getObject(i));
                }
                data.addElement(row);
                System.out.println(data);
            }   
            rs.close();


    for (int i=0; i<spTable.getColumnCount(); i++){
        column=spTable.getColumnModel().getColumn(i);
        //column.setMaxWidth(250);

    }


        }


     statement.close();
    } catch (SQLException e) {
        System.err.println("An exception ocurred");
        System.err.println(e.getMessage());

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(realEstateUI.class.getName()).log(Level.SEVERE, null, ex);
    }


  JOptionPane.showMessageDialog(this,"Query Complete");
}                                                               

/**

1 个答案:

答案 0 :(得分:3)

您正在尝试在UI可见后添加JTable。要使添加生效,您必须拨打revalidate,然后拨打repaint。作为替代方案,在UI构建时(在可见之前)添加JTable并在JTable

中填充salePropertyActionPerformed的模型