【问题标题】:JTable refreshed data not displayedJTable刷新数据不显示
【发布时间】:2013-02-15 10:02:23
【问题描述】:

这是一个 JDBC 项目。来自 WAMP 服务器上的 mySql 数据库的数据显示在 jtable 中。现在我想要在我的 Spinnerbutton 上用户输入的 ID 并删除具有该 ID 的行。我做了一个 SQL 查询,一切正常,但是执行查询时 myjtable 上的数据不会刷新。我单击我的 JNazad 按钮(我的后退按钮),然后重新进入该窗口,以便我的 Jtable 显示刷新的数据。我想我没有在 NapraviTablicu 方法中正确实现 FireTableModel,但不知道我做错了什么:

public class GUIBDelete extends JFrame{

    private SpinnerModel SM;
    private JSpinner Spinner;
    private JLabel LUnos;
    private JButton BNazad, BIzvrsi;
    private String ID, SqlQuery;
    private Vector NaziviKolona = new Vector();
    private Vector Podaci = new Vector();
    private JTable Tablica=new JTable();
    private JScrollPane ScrollPane;
    private DefaultTableModel model;


    private JTable NapraviTablicu(){
        try {
            String SqlQuery = "SELECT * FROM `nfc_baza`";
            Podaci.clear();
            NaziviKolona.clear();
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:mysql://"
                    + "localhost:3306/nfc", "root", "");

            Statement Stat = con.createStatement();
            ResultSet Rez = Stat.executeQuery(SqlQuery);
            ResultSetMetaData md = Rez.getMetaData();
            int columns = md.getColumnCount();
            for (int i = 1; i <= columns; i++) {
                NaziviKolona.addElement(md.getColumnName(i));
            }
            while (Rez.next()) {
                Vector red = new Vector(columns);
                for (int i = 1; i <= columns; i++) {
                    red.addElement(Rez.getObject(i));
                }
                Podaci.addElement(red);
            }
            Rez.close();
            Stat.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        model = new DefaultTableModel(Podaci, NaziviKolona);
        model.fireTableDataChanged();
        JTable table = new JTable(model);

        return table;

    }

    ActionListener a1 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            dispose();
            new GUIIzbornik();
        }
    };

    ActionListener a2 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            ID=null;
            SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
            IzvrsiQuery();
            model.fireTableDataChanged();
        }

        private void IzvrsiQuery() {
            Object sp = Spinner.getValue();
            ID = sp.toString();
            SqlQuery=SqlQuery+ID;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con2 = DriverManager.getConnection(
                        "jdbc:mysql://" + "localhost:3306/nfc", "root", "");
                Statement Stat = con2.createStatement();
                int Rez = Stat.executeUpdate(SqlQuery);
                Stat.close();
                con2.close();
                JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
                        "Poruka!", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                System.out.println(e);
            }


        }

    };


    GUIBDelete(){
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        Tablica=NapraviTablicu();
        ScrollPane = new JScrollPane(Tablica);
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(2, 2, 2, 2);
        c.weightx = 0.1;
        c.weighty = 0.1;
        c.gridwidth = 4;
        c.gridheight = 2;
        c.gridx = 0;
        c.gridy = 0;
        add(ScrollPane, c);


        LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        c.gridheight = 1;
        add(LUnos, c);

        SM = new SpinnerNumberModel(1, 1, 1000, 1);
        Spinner = new JSpinner(SM);
        c.gridx = 2;
        c.gridy = 2;
        c.gridwidth = 1;
        add(Spinner, c);

        BNazad = new JButton("Nazad");
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        BNazad.addActionListener(a1);
        add(BNazad, c);

        BIzvrsi = new JButton("Izvrši");
        c.gridx = 3;
        c.gridy = 3;
        BIzvrsi.addActionListener(a2);
        add(BIzvrsi, c);

        setSize(400, 500);
        setTitle("Brisanje podataka");
        setVisible(true);
        setLocationRelativeTo(null);

    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUIBDelete i = new GUIBDelete();
            }
        });
    }
}

首先,非常感谢您的回答!

当我使用PreparedStatement 时,我得到了这个异常:

java.lang.ClassCastException: com.mysql.jdbc.StatementImpl cannot be 
  cast to java.sql.PreparedStatement 

..所以我必须使用经典的Statement

我也试过不每次都创建JTable,我只是在我的NapraviTablicu方法中创建模型,然后在我的构造函数中使用该模型,只需将它添加到表Tablica,但现在表是没有显示任何数据。我不知道我是否在我的代码中正确地实现了你的提示......

public class GUIBDelete extends JFrame{

    private SpinnerModel SM;
    private JSpinner Spinner;
    private JLabel LUnos;
    private JButton BNazad, BIzvrsi;
    private String ID, SqlQuery;
    private Vector NaziviKolona = new Vector();
    private Vector Podaci = new Vector();
    private JTable Tablica=new JTable();
    private JScrollPane ScrollPane;
    private DefaultTableModel model;


    private void NapraviTablicu(){
        try {
            String SqlQuery = "SELECT * FROM `nfc_baza`";
            Podaci.clear();
            NaziviKolona.clear();
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://"
                    + "localhost:3306/nfc", "root", "");

            Statement Stat = con.createStatement();
            ResultSet Rez = Stat.executeQuery(SqlQuery);
            ResultSetMetaData md = Rez.getMetaData();
            int columns = md.getColumnCount();
            for (int i = 1; i <= columns; i++) {
                NaziviKolona.addElement(md.getColumnName(i));
            }
            while (Rez.next()) {
                Vector red = new Vector(columns);
                for (int i = 1; i <= columns; i++) {
                    red.addElement(Rez.getObject(i));
                }
                Podaci.addElement(red);
            }
            Rez.close();
            Stat.close();
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
        model = new DefaultTableModel(Podaci, NaziviKolona);
        //model.fireTableDataChanged();

    }

    ActionListener a1 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            dispose();
            new GUIIzbornik();
        }
    };

    ActionListener a2 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            ID=null;
            SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
            IzvrsiQuery();
            //model.fireTableDataChanged();
        }

        private void IzvrsiQuery() {
            Object sp = Spinner.getValue();
            ID = sp.toString();
            SqlQuery=SqlQuery+ID;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con2 = DriverManager.getConnection(
                        "jdbc:mysql://" + "localhost:3306/nfc", "root", "");
                PreparedStatement Stat = (PreparedStatement) con2.createStatement();
                int Rez = Stat.executeUpdate(SqlQuery);
                Stat.close();
                con2.close();
                JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
                        "Poruka!", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                System.out.println(e);
            }


        }

    };


    GUIBDelete(){
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        Tablica=new JTable(model);
        ScrollPane = new JScrollPane(Tablica);
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(2, 2, 2, 2);
        c.weightx = 0.1;
        c.weighty = 0.1;
        c.gridwidth = 4;
        c.gridheight = 2;
        c.gridx = 0;
        c.gridy = 0;
        add(ScrollPane, c);


        LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        c.gridheight = 1;
        add(LUnos, c);

        SM = new SpinnerNumberModel(1, 1, 1000, 1);
        Spinner = new JSpinner(SM);
        c.gridx = 2;
        c.gridy = 2;
        c.gridwidth = 1;
        add(Spinner, c);

        BNazad = new JButton("Nazad");
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        BNazad.addActionListener(a1);
        add(BNazad, c);

        BIzvrsi = new JButton("Izvrši");
        c.gridx = 3;
        c.gridy = 3;
        BIzvrsi.addActionListener(a2);
        add(BIzvrsi, c);

        setSize(400, 500);
        setTitle("Brisanje podataka");
        setVisible(true);
        setLocationRelativeTo(null);

    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUIBDelete i = new GUIBDelete();
            }
        });
    }
}

【问题讨论】:

  • 请学习java命名约定并遵守它们。

标签: java mysql swing jdbc jtable


【解决方案1】:

您需要使用com.mysql.jdbc.Driver 作为您的JDBC 驱动程序,而不是通用的JDBC/ODBC 驱动程序。也无需调用fireTableDataChanged,您的TableModel 会在后台调用它。


旁注:

  • 无需每次都创建JTableDefaultTableModel 是一个可变的 TableModel,可以更新。
  • PreparedStatement 被认为比 Statement 更安全
  • 如果您不添加新功能,则无需扩展 JFrame。首选直接实例。
  • 为了可维护性,请考虑将您的数据库/非 UI 代码与您的 UI 代码分开。

更新:

要创建PreparedStatement,请使用Connection#prepareStatement 而不是Connection#createStatement

PreparedStatement Stat = con2.prepareStatement(SqlQuery);

那么在执行查询的时候,需要使用execute语句加上empty 参数列表:

int rez = stat.executeUpdate();

最好将Statement & Connection & close 语句放在finally 块中。 Java 对变量名称使用初始 小写 字母,这将使 SqlQuery sqlQuery

【讨论】:

  • 也无需重新创建表格,只需更改表格模型即可更新 ui +1 - 此外,SwingWorker 将有助于在您获取值时阻止 UI “停止”数据库...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 2012-09-21
  • 2014-10-09
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多