数据库插入后JTable不刷新

时间:2013-11-09 19:48:35

标签: java database swing jtable tablemodel

我真的需要你的帮助,我试图解决这个问题超过一周,但还没有找到解决方案。

我的目标:我想创建一个表,它可以从数据库中读取数据。我也可以通过将数据插入我的程序中来将数据添加到数据库中。

我的问题:插入数据后我希望数据库刷新,这样它也会显示我的新记录集。但不管我尝试了什么,都没有用。

我的代码:这是我的Mainframe-Class:

public class Gui_Test extends JFrame {

JButton addMovieButton;
JFrame frame = new JFrame("Movie Database");

JPanel panel;
JMenuBar menubar;
JMenu fileMenu;
JLabel label;
JTable table = new JTable();
MovieTableModel mtm;

public static void main(String[] args) {
    Gui_Test test = new Gui_Test();
    test.run();

}

public void run() {

    // Gui ///

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);

    panel = new JPanel();
    panel.setVisible(true);
    panel.setBackground(Color.black);

    // Add - Movie Button ///

    addMovieButton = new JButton("Add Movie");
    addMovieButton.addActionListener(new addMovieButtonListener());
    panel.add(addMovieButton);

    // Table select ///

    mtm = new MovieTableModel();
    table.setModel(mtm);

    JScrollPane pane = new JScrollPane(table);
    frame.getContentPane().add(pane);
    frame.getContentPane().add(BorderLayout.WEST, panel);

}

class addMovieButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        AddMoviePanel addmoviepanel = new AddMoviePanel();
        addmoviepanel.moviepanel(mtm);

    }
}}

这是我的TableModel:

public class MovieTableModel extends AbstractTableModel {

Connection con = null;
Vector columnNames = new Vector();
Vector data = new Vector();
ResultSet rs;
ResultSetMetaData meta;

public MovieTableModel() {

    showResult();
}

void showResult() {

    Connection con;

    try {
        con = DriverManager.getConnection(
                "jdbc:hsqldb:file:C:/Users/...", "sa",
                "");

        java.sql.Statement stmt = con.createStatement();
        String query = "SELECT * FROM movies ORDER BY id DESC";
        ResultSet rs = stmt.executeQuery(query);
        meta = rs.getMetaData();

        int columns = meta.getColumnCount();

        // get column names
        for (int i = 1; i <= columns; i++) {
            columnNames.addElement(meta.getColumnName(i));
        }

        // get row data

        while (rs.next()) {
            Vector row = new Vector(columns);
            for (int i = 1; i <= columns; i++) {
                row.addElement(rs.getObject(i));
            }
            data.addElement(row);
        }

        if (con != null)
            try {
                rs.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    } catch (SQLException e1) {
        e1.printStackTrace();
    }
}

@Override
public String getColumnName(int column) {

    return columnNames.get(column).toString();

}

@Override
public int getColumnCount() {

    try {
        return meta.getColumnCount();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return 0;
}

@Override
public Class getColumnClass(int column) {
    // TODO Auto-generated method stub
    return getValueAt(0, column).getClass();
}

@Override
public int getRowCount() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public Object getValueAt(int row, int column) {

    return ((Vector) data.get(row)).get(column);

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {

    return false;
}

void addRow(final String value1, final String value2, final String value3,
        final String value4, final String value5, final String value6,
        final String value7) {

    try {

        Connection con = DriverManager.getConnection(
                "jdbc:hsqldb:file:C:/Users/Jonas/workspace/movieDB", "sa",
                "");

        try {

            final java.sql.Statement state = con.createStatement();

            try {
                state.addBatch("INSERT INTO movies VALUES (DEFAULT, '"
                        + value1 + "', '" + value2 + "'," + value3 + ", '"
                        + value4 + "', " + value5 + ", '" + value6 + "', '"
                        + value7 + "')");

                state.executeBatch();

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

        } catch (SQLException e) {
            e.printStackTrace();
        }
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    } finally {
        if (con != null)
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

}}

这是我的addMovieFrame,它会打开以添加新电影:

public class AddMoviePanel {

MovieTableModel mtm;

JPanel addMoviePanel;
JFrame addMovieFrame;

JTextField value1Input;
JTextField value2Input;
// ... value3 - value7

Connection con = null;

public void moviepanel(MovieTableModel mtm) {

    this.mtm = mtm;
    addMovieFrame = new JFrame("Add Movie");
    addMovieFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addMovieFrame.setVisible(true);
    addMovieFrame.setSize(550, 300);

    addMoviePanel = new JPanel();

    GroupLayout layout = new GroupLayout(addMoviePanel);
    addMoviePanel.setLayout(layout);

    JLabel label1 = new JLabel("label1:");
    JLabel label2 = new JLabel("label2");
    // ...JLabel 3-7 same as Label 1&2

    addMoviePanel.add(label1);
    addMoviePanel.add(label2);
    // ...add Label 3-7

    value1Input = new JTextField();
    value2Input = new JTextField();
    // ... value3- value7 Input

    addMoviePanel.add(value1Input);
    addMoviePanel.add(value2Input);
    // ... add value3Input - value7Input

    JButton ok = new JButton("Ok");

    ok.addActionListener(new okActionListener());
    addMovieFrame.add(ok);

    addMovieFrame.getContentPane().add(addMoviePanel);

    // here was just Layout Stuff //
}

class okActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        mtm.addRow(value1Input.getText(), value2Input.getText()
                // ... value3Input.getText() - value7Input.getText()
                );

        mtm.fireTableDataChanged();

        addMovieFrame.dispose();
    }

}}

我已经尝试了几种类型和位置的fireXXX-Methods ......

当我在addMovie-Frame中点击OK按钮时,也许有人知道如何刷新我的jtable? :)

1 个答案:

答案 0 :(得分:1)

here和discuseed here所示,只有您的TableModel应该触发表模型事件。虽然这通常在setValueAt()中完成,但您可以插入整行并触发单个事件,如here所示。