SQL数据不会出现在JTable中

时间:2017-06-05 14:22:28

标签: java sql swing jtable

我有一个程序,当用户点击按钮时,数据库中的SQL数据显示在JTable中。问题是当我点击按钮时没有显示任何内容。但是当我打印变量时,它确实显示了正确的值。那么为什么我的JTable中出现了什么?

注意:JTable / Button添加了GUI设计。

代码:

import connection.connection;
import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author peter
 */
public class Tabel extends javax.swing.JFrame {

    /**
     * Creates new form Tabel
     */
    public Tabel() {
        initComponents();
    }                      

    private void showBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
                            "capaciteit"};

        String sql = "SELECT * FROM uitgiftepunt";

        try (
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
            ){
               DefaultTableModel model = new DefaultTableModel(columns, 0);
                while (rs.next()) {
                    int nummer = rs.getObject("nummer", Integer.class);
                    String adres = rs.getObject("adres", String.class);
                    String postcode = rs.getObject("postcode", String.class);
                    String plaats = rs.getObject("plaats", String.class);
                    int cap = rs.getObject("capaciteit", Integer.class);
                    model.addRow(new Object[]{nummer,adres,postcode,plaats,cap});   
                    System.out.printf("%d, %s, %s, %s, %d", nummer,adres,postcode,plaats,cap);

                }

                jTable1.setModel(model);
                jScrollPane1 = new JScrollPane(jTable1);
                jTable1.setFillsViewportHeight(true);


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

    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {



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

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton showBtn;
    // End of variables declaration                   
}

2 个答案:

答案 0 :(得分:0)

这是一个有保证的解决方案,除非您有日志中显示的SQL异常 重复使用此代码段,特别是createView()和buildtabalemodel函数。

public class JTableSQLProblem extends JFrame{
JScrollPane scrollPane;

public JTableSQLProblem(){
    setSize(1000,500);
    setLayout( new FlowLayout());

    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(createView());

    add(scrollPane);
    repaint();
    setVisible(true);
}
  public static DefaultTableModel buildtableModel(ResultSet resultSet) throws SQLException {

    ResultSetMetaData metaData = resultSet.getMetaData();

    Vector<String> columnNames = new Vector<>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));

    }

    Vector<Vector<Object>> data = new Vector<>();
    while (resultSet.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(resultSet.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}
 private static JTable createView() {
    try {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/youtdatabasename","root","");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(
                "SELECT * FROM yourtablename");

        JTable table = new JTable(buildtableModel(rs));
        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        defaults.put("Table.alternateRowColor", Color.decode("#f5f5f5"));
        table.setSelectionBackground(Color.decode("#1e90ff"));
        table.setSelectionForeground(Color.WHITE);
        table.setRowHeight(30);
        table.setBackground(Color.WHITE);
        table.setShowGrid(false);
        table.setFont(new Font("calibri", Font.PLAIN, 16));

        JTableHeader tableHeader = table.getTableHeader();
        tableHeader.setBackground(Color.decode("#B0E0E6"));
        tableHeader.setForeground(Color.black);
        tableHeader.setFont(new Font("Calibri Bold", Font.BOLD, 14));
        tableHeader.setBorder(new LineBorder(Color.WHITE));

        rs.close();
        return table;
    } catch (SQLException | HeadlessException exc) {
        JOptionPane.showMessageDialog(null, exc);
        return new JTable();
    }
}
public static void main(String[]args){
    new JTableSQLProblem();
}}

答案 1 :(得分:0)

我建议创建一个单独的方法来创建表

public static DefaultTableModel buildTableModel(ResultSet rs)throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);
}

通过这种方式,您可以创建一个新的DefaultTableModel,将data和columnNames作为参数传递,第一个是Vector of Vector,第二个是Vector

然后

ResultSet rs = stmt.executeQuery(query);
JTable table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);

在上一张表中,我使用的是我的问题,表格没有填充,直到我用鼠标弄乱它,这是另一个问题,如果你面对它你可以通过向下或向上滚动1来解决它创建表格后的像素