How to populate the data to Jtable from database directly

后端 未结 2 800
小鲜肉
小鲜肉 2021-01-16 01:23

I have display the Jtable depends on the particular column from database and final two column in my jtable is image fields.How can i change the column dynamically without af

相关标签:
2条回答
  • 2021-01-16 02:16

    Use Vector from java.util.Collection

    See this example from http://www.roseindia.com

    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.TableColumn;
    
    public class JTableResultSet {
        public static void main(String[] args) {
            Vector columnNames = new Vector();
            Vector data = new Vector();
            JPanel panel = new JPanel();   //
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                Connection con = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/test", "root", "root");
                String sql = "Select name,address from user";
                Statement statement = con.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columns = metaData.getColumnCount();
                for (int i = 1; i <= columns; i++) {
                    columnNames.addElement(metaData.getColumnName(i));
                }
                while (resultSet.next()) {
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++) {
                        row.addElement(resultSet.getObject(i));
                    }
                    data.addElement(row);
                }
                resultSet.close();
                statement.close();
            } catch (Exception e) {
                System.out.println(e);
            }
            JTable table = new JTable(data, columnNames);
            TableColumn column;
            for (int i = 0; i < table.getColumnCount(); i++) {
                column = table.getColumnModel().getColumn(i);
                column.setMaxWidth(250);
            }
            JScrollPane scrollPane = new JScrollPane(table);        panel.add(scrollPane);               
            JFrame frame = new JFrame();
            frame.add(panel);         //adding panel to the frame
            frame.setSize(600, 400); //setting frame size
            frame.setVisible(true);  //setting visibility true
        }
    }
    
    0 讨论(0)
  • TableModel.setValueAt(Objet value, int row, int col)

    0 讨论(0)
提交回复
热议问题