JTable仅在一列中显示所有记录(数据)吗?

时间:2018-10-11 08:04:54

标签: java swing jdbc jtable

在代码中,JTable从具有一个表和两个列的数据库中检索所有数据。

该程序只是一个最小的示例。数据库(Javadb)“ SOMETABLE”,表“ TESTTABLE”,第一列“ DATA1”(字符),第二列“ DATA2”(字符)。

程序从命令行获取并显示输入和记录。其余的在Gui上完成。首先获取DATA1和DATA2的输入,然后单击“保存”,然后通过单击“加载”显示记录。

然后单击Del,以显示JTable上的记录。只需在GUI和CLI之间切换。

但是当我执行程序时,JTable仅将所有数据显示在一个列中,而不是两个列中?

很抱歉造成误会。

public class DBtest {
    JFrame f;
    JPanel p1;
    JPanel p2;
    JPanel p3;
    JButton b1;
    JButton b2;
    JButton b3;
    JMenuItem delete;
    JPopupMenu pm;
    JTable t;
    String[] c = {
        "DATA1",
        "DATA2"
    };
    Object[][] obj = null;
    Object o1;
    Object o2;
    int n;
    Scanner sc;
    String s1;
    String s2;
    Object row2Delete;
    Connection con;
    PreparedStatement ps;
    Connection con1;
    PreparedStatement ps1;
    Connection con2;
    PreparedStatement ps2;
    Connection con3;
    PreparedStatement ps3;
    ResultSet rs;
    ResultSet rs2;

    public static void main(String[] args) {
        new DBtest().startApp();
    }

    public void startApp() {
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        b1 = new JButton("Save");
        b1.addActionListener(new SaveListener());
        b2 = new JButton("Load");
        b2.addActionListener(new LoadListener());
        b3 = new JButton("Del");
        b3.addActionListener(new DelListener());
        t = new JTable(obj, c);
        pm = new JPopupMenu();
        delete = new JMenuItem("Delete ?");
        delete.addActionListener(new DeleteListener());
        pm.add(delete);

        p1.setLayout(new BorderLayout());
        p1.add(p2, BorderLayout.NORTH);
        p2.setLayout(new FlowLayout());
        p2.add(b1);
        p2.add(b2);
        p2.add(b3);

        f = new JFrame();
        f.getContentPane().add(p1);
        f.setTitle("Database");
        f.setSize(450, 550);
        f.setResizable(false);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        sc = new Scanner(System.in);
        System.out.println("Type something");
        s1 = sc.nextLine();
        System.out.println("Type again");
        s2 = sc.nextLine();
        sc.close();
    }



    public class DelListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent ev) {
            try {
                tableView(); //filling the table
                boolean DEBUG = false;
                boolean ALLOW_COLUMN_SELECTION = false;
                boolean ALLOW_ROW_SELECTION = true;

                t.setPreferredScrollableViewportSize(new Dimension(500, 70));
                t.setFillsViewportHeight(true);
                t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                if (ALLOW_ROW_SELECTION) {
                    ListSelectionModel rowSM = t.getSelectionModel();
                    rowSM.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                            if (e.getValueIsAdjusting()) return;
                            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                            if (lsm.isSelectionEmpty()) {
                                System.out.println("No rows are selected");
                            } else {
                                int selectedRow = lsm.getMinSelectionIndex();
                                pm.show(t, 50, 50);
                                System.out.println("Row  " + selectedRow + " is now selected");
                            }
                        }
                    });
                }
                JScrollPane scrollPane = new JScrollPane(t);
                p1.add(scrollPane, BorderLayout.CENTER);
                f.validate();
            } catch (SQLException ex) {
                Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    public void tableView() throws SQLException, ClassNotFoundException {

        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
        con1.commit();
        String sql = "SELECT DATA1 FROM ME.SOMETABLE";
        ps1 = con1.prepareStatement(sql);
        rs = ps1.executeQuery();

        con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
        con2.commit();
        String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
        ps2 = con2.prepareStatement(sql2);
        rs2 = ps2.executeQuery();

        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();
        ResultSetMetaData metaData2 = rs2.getMetaData();
        //Get number of columns from meta data
        int columnCount = metaData.getColumnCount();
        int columnCount2 = metaData2.getColumnCount();
        //Get all column names from meta data and add columns to table model
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }
        for (int columnIndex = 1; columnIndex <= columnCount2; columnIndex++) {
            tableModel.addColumn(metaData2.getColumnLabel(columnIndex));
        }
        //Create array of Objects with size of column count from meta data
        Object[] row = new Object[columnCount];
        Object[] row2 = new Object[columnCount2];
        //Scroll through result set
        while (rs.next() && rs2.next()) {
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++) {
                row[i] = rs.getObject(i + 1);
                for (int h = 0; h < columnCount2; h++) {
                    row2[h] = rs2.getObject(h + 1);
                }
            }
            //Add row to table model with that array of objects as an argument
            tableModel.addRow(row);
            tableModel.addRow(row2);
        }

        //Now add that table model to your table
        t.setModel(tableModel);
        t.setAutoCreateRowSorter(true);
    }




    public class DeleteListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent ev) {
            try {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                con3 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
                con3.commit();
                String sql = "DELETE FROM ME.SOMETABLE WHERE DATA1=?";
                int row = t.getSelectedRow();
                int column = t.getColumnCount();
                for (int i = 0; i < column; i++) {
                    row2Delete = t.getValueAt(row, i);
                }

                ps3 = con3.prepareStatement(sql);
                ps3.setString(1, "+row2Delete+");

                int rowsDeleted = ps3.executeUpdate();
                System.out.println("Row deleted: " + "  " + rowsDeleted);
                if (rowsDeleted > 0) {
                    System.out.println(" delete successfully!");
                }
                ps3.clearParameters();
            } catch (SQLException ex) {
                Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (ps3 != null) con3.close();
                    if (con3 != null) con3.close();
                } catch (SQLException ex) {
                    Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public class SaveListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent ev) {
            try {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                con = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
                con.commit();
                //System.out.println(textAreaText() + "\n");
                String sql = "INSERT INTO SOMETABLE (DATA1, DATA2)" + "VALUES (?,?)";
                ps = con.prepareStatement(sql);
                ps.setString(1, s1);
                ps.setString(2, s2);
                ps.executeUpdate();
                ps.clearParameters();
            } catch (SQLException es) {
                es.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (ps != null) con.close();
                    if (con != null) con.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    public class LoadListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent ev) {
            try {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
                con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
                con1.commit();
                String sql = "SELECT DATA1 FROM ME.SOMETABLE";
                ps1 = con1.prepareStatement(sql);
                rs = ps1.executeQuery();

                con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
                con2.commit();
                String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
                ps2 = con2.prepareStatement(sql2);
                rs2 = ps2.executeQuery();
                ResultSetMetaData rsmd = rs.getMetaData();

                while (rs.next() && rs2.next()) {
                    for (int z = 0; z < rsmd.getColumnCount(); z++) {
                        n = z + 1;
                        o1 = rs.getObject(z + 1);
                        o2 = rs2.getObject(z + 1);
                        System.out.println(rs.getObject(z + 1) + "\n");
                        System.out.println(rs2.getObject(z + 1) + "\n");
                    }
                }
                ps1.clearParameters();
                ps2.clearParameters();
            } catch (SQLException es) {
                es.printStackTrace();
            } catch (Exception ex) {} finally {
                try {
                    if (ps2 != null) con2.close();
                    if (con2 != null) con2.close();
                    if (ps1 != null) con1.close();
                    if (con1 != null) con1.close();
                } catch (SQLException ex) {
                    Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的tableView方法没有任何意义。为什么要打开两个数据连接,在同一个表上运行两个不同的查询,然后尝试合并它们?

您还冒着资源泄漏的风险(使数据库连接保持打开状态),从长远来看,这种情况不会持续良好。

该问题的简单答案是正确使用SQL。在数据库中以尽可能少的语句从所需的表中查询所需的列。例如...

public void tableView() throws SQLException, ClassNotFoundException {
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

    //Create new table model
    DefaultTableModel tableModel = new DefaultTableModel();

    try (Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234")) {
        String sql = "SELECT DATA1, DATA2 FROM ME.SOMETABLE";
        try (PreparedStatement ps = con.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                List<String> columnNames = new ArrayList<>(columnCount);
                for (int column = 0; column < columnCount; column++) {
                    columnNames.add(rsmd.getColumnName(column + 1));
                }

                tableModel.setColumnIdentifiers(columnNames.toArray(new Object[columnNames.size()]));

                while (rs.next()) {
                    Object row[] = new Object[columnCount];
                    for (int column = 0; column < columnCount; column++) {
                        row[column] = rs.getObject(column + 1);
                    }
                    tableModel.addRow(row);
                }
            }
        } finally {
            t.setModel(tableModel);
        }
    }
}

也请查看try-with-resources,以获得更好的资源管理方式...