JTable不会重新/刷新数据插入到mysql中

时间:2014-02-26 13:45:41

标签: java swing jdbc jtable defaulttablemodel

我不确定我做错了什么,但我从MySQL db获取数据并使用DefaultTableModel填充JTable。然后我在屏幕上显示它。将数据从文本框添加到数据库后,JTable不会刷新。我检查了数据库,插入的数据就在那里。我在事件监听器中尝试使用table.repaint()dTableModel.fireTableDataChanged()添加按钮,但仍然没有。这是代码:

public class DbTable {

    private JLabel lFirstName, lLastName, lState, lBirthDate;
    private JTextField fFirstName, tLastName, tState, tBirthDate;
    private JButton btnAdd;
    private Object[][] databaseResults;
    private Object[] columns = { "Col 1", "Col 2", "Col 3", "Col 4",
            "Col 5", "ЈCol 6", "Col 7" };
    private ResultSet rows;
    private ResultSet rowsCb;

    private JComboBox combobox;


    private DefaultTableModel dTableModel = new DefaultTableModel(
            databaseResults, columns) {
        public Class getColumnClass(int column) {
            Class returnValue; 

            if ((column >= 0) && (column < getColumnCount())) {
                returnValue = getValueAt(0, column).getClass();
            } else { 
                returnValue = Object.class;
            }
            return returnValue;
        }
    };

    private JTable table = new JTable(dTableModel);
    Connection conn = null;
    public static void main(String[] args) {
        DbTable dbTable = new DbTable();

        dbTable.getTable();
    }

    public void getTable() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost/database", "root", "");

            Statement sqlState = conn.createStatement(
                    ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);

            String selectStuff = "SELECT  `invoice`.`id` ,  `client`, `date`, `project`, `amount`,`unitPrice`, `total`"
                    + "FROM  `invoice` ,  `clients`"
                    + "WHERE  `invoice`.`clientID` =  `clients`.`id`"
                    + "ORDER BY  `invoice`.`id` ASC ";

            rows = sqlState.executeQuery(selectStuff);

            Object[] tempRow;

            while (rows.next()) {
                tempRow = new Object[] { rows.getInt(1), rows.getString(2),
                        rows.getString(3), rows.getString(4), rows.getInt(5),
                        rows.getInt(6), rows.getDouble(7) };
                dTableModel.addRow(tempRow);

            }

        } catch (SQLException e) {
            e.getMessage();
        } catch (ClassNotFoundException e) {
            e.getMessage();
        }

        table.setFont(new Font("Tahoma", Font.PLAIN, 14));
        table.setAutoCreateRowSorter(true);

        JScrollPane scrollPane = new JScrollPane(table);
        // frame.add(combobox, BorderLayout.NORTH);

        frame.add(scrollPane, BorderLayout.NORTH);
        // Define values for my labels
        lFirstName = new JLabel("Klijent ID: ");
        lLastName = new JLabel("Datum: ");
        lState = new JLabel("Projekat: ");
        lBirthDate = new JLabel("Ukupno"); // Define the size of text fields
        fFirstName = new JTextField(10);
        tLastName = new JTextField(10);
        tBirthDate = new JTextField(10);
        tState = new JTextField(10);
        btnAdd = new JButton("Add");

        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String sDatum = "", sProjekat = "";
                int sKlijenId;
                double sUkupno = 0.00;
                sKlijenId = Integer.parseInt(fFirstName.getText());
                sDatum = tLastName.getText();
                sProjekat = tState.getText();
                sUkupno = Double.parseDouble(tBirthDate.getText());

                try {
                    Class.forName("com.mysql.jdbc.Driver");

                    conn = DriverManager.getConnection(
                            "jdbc:mysql://localhost/sjajplusz", "root", "");

                    Statement sqlState = conn.createStatement(
                            ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_UPDATABLE);

                    String selectStuff = "SELECT * FROM invoice";

                    rows = sqlState.executeQuery(selectStuff);

                    rows.moveToInsertRow();
                    rows.updateInt("clientID", sKlijenId);
                    rows.updateString("date", sDatum);
                    rows.updateString("project", sProjekat);
                    rows.updateDouble("total", sUkupno);

                    rows.insertRow();
                    rows.updateRow();

                } catch (SQLException e1) {
                    e1.getMessage();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                int invoiceId = 0;

                try {
                    rows.last();
                    invoiceId = rows.getInt(1);
                } catch (SQLException e) {
                    e.getMessage();
                }


//              Object[] invoice = {invoiceId, sKlijenId, sDatum, sProjekat, "", "", sUkupno};
//              
//              dTableModel.addRow(invoice);

                dTableModel.fireTableDataChanged();

            }
        });

        JPanel inputPanel = new JPanel(); // Put components in the panel
        inputPanel.add(lFirstName);
        inputPanel.add(fFirstName);
        inputPanel.add(lLastName);
        inputPanel.add(tLastName);
        inputPanel.add(lState);
        inputPanel.add(tState);
        inputPanel.add(lBirthDate);
        inputPanel.add(tBirthDate);
        inputPanel.add(btnAdd);

        frame.add(inputPanel, BorderLayout.SOUTH);

        // frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 400);
        frame.setVisible(true);

        try {
            conn.close();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

基本上这是对此YouTube系列Java JTable 38

的跟进

1 个答案:

答案 0 :(得分:-1)

您没有从数据库重新加载数据。将数据添加到数据库后,您必须重新加载数据,刷新DefaultTableModel,然后调用fireTableDataChanged()。您最初只是在getTable()方法中执行此操作。您必须提取加载数据的代码并在动作监听器中调用它。

顺便说一下。即使插入数据的方式也很复杂,你的代码组织得不是很好。我建议你做一些基本的教程。