JTable列名不能打印

时间:2013-10-15 00:15:32

标签: java mysql swing

当我创建2个向量(数据,列名)并在JTable中使用它们来显示带有列标题的行时,它只显示行而不是列标题。

在JOptionPane中,列标题显示正常。我假设在哪里出现错误,因为它没有正确地获得列名。

public void displayLettingProperties()抛出SQLException {

    Connection conn = null;
    try {       
        conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
        System.out.println("Connected to database.");       

         // The Connection is obtained

        Statement Stmt = (Statement) conn.createStatement();
    //  Stmt.execute(createPropertyTable);

        ResultSet rs = Stmt.executeQuery("select * from PropertyLettings ORDER BY propertyBedrooms ASC");

        // It creates and displays the table
        **JTable table = new JTable(buildTableModel(rs));**


     // Set Column Widths

        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(2).setPreferredWidth(350);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(100);
        table.getColumnModel().getColumn(5).setPreferredWidth(350);
        table.getColumnModel().getColumn(6).setPreferredWidth(100);
        table.getColumnModel().getColumn(7).setPreferredWidth(130);



     //   JOptionPane.showMessageDialog(null, new JScrollPane(table));

        final JPanel panelOne = new JPanel();
        panelOne.setVisible(true);
        panelOne.setBackground(Color.LIGHT_GRAY);
        // JFRAME
        final JFrame topFrame = new JFrame();
        topFrame.setSize(1550, 300);
        topFrame.setLocationRelativeTo ( null );
        topFrame.setVisible(true);
        topFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


        // PUT TOGETHER
        topFrame.add(panelOne);

        panelOne.add(table);


        panelOne.revalidate();
        panelOne.repaint();


    } catch (SQLException e) {
        System.err.println("Cannot connect to database." + e);


    } finally {

    if(conn != null){
        conn.close();

      }

    } 

1 个答案:

答案 0 :(得分:2)

正如您在previous question中使用此代码所建议的那样,您需要在添加到用户界面之前将表格添加到JScrollPane

panelOne.add(new JScrollPane(table));

请查看How to use scroll panesHow to use tables了解详情......