Question

I use DefaultTableModel for my JTable model, But not show my table!

public class RecordTableGUI2 extends JFrame {

JTable table;
RecordTableModel2 model2;

public RecordTableGUI2() {
    model2 = new RecordTableModel2();
    table = new JTable(model2);

    add(new JScrollPane(table), BorderLayout.CENTER);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new RecordTableGUI2();
        }
    });
}
}

Model Class:

public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();


public RecordTableModel2() {
    try {
        con = DriverManager.getConnection(dbUrl, "root", "2323");
        statement = con.createStatement();
        result = statement.executeQuery(query);

        int c = result.getMetaData().getColumnCount();
        for (int i = 1; i <= c; i++) {
            column.add(result.getMetaData().getColumnName(i));
            System.out.println(result.getMetaData().getColumnName(i)); //prints correct
        }

        while (result.next()) {
            Vector eachRow = new Vector(c);
            for (int i = 1; i <= c; i++) {
                eachRow.add(result.getString(i));
                System.out.println(result.getString(i));  //prints correct
            }
            data.add(eachRow);
        }

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    } finally {
        try {
            if (con != null) {
                con.close();
            }
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException sqlee) {
            sqlee.printStackTrace();
        }
    }
}
}

How to introduce vectors to DefaultTableModel?

Output just show a blank JFrame

Was it helpful?

Solution

Add this at first statement of constructor:

super(data,column);

And declare data and column as static

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top