如何从数据库刷新gui中的JTable?

发布于 2025-01-04 20:28:39 字数 8963 浏览 1 评论 0原文

在这里我连接我的数据库:

package org.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class dbconnect {

    public static Connection getConnectionvalue() {
        Statement stmt = null;
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            con = DriverManager.getConnection(url, "system", "kingdom");
            con.setAutoCommit(true);
        } catch (Exception e) {
            System.out.println("Connection Error" + e);
        }
        return con;
    }

    public static Statement
    getStatementvalue() {
        Statement stmt = null;
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            con = DriverManager.getConnection(url, "system", "kingdom");
            con.setAutoCommit(true);
            stmt = con.createStatement();
        } catch (Exception e) {
            System.out.println("Connection Error" + e);
        }
        return stmt;
    }
}

在这里我创建了框架并获取数据库表值。然后我将表值的结果集传递给 Deptmodeltable

package org.frames.src;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.connect.dbconnect;
import org.reports.master.TESTJASPER;
import org.table.model.DeptTableModel;

import java.awt.event.ActionListener;
import java.io.IOException;

public class DeptFrame extends JFrame implements RowSetListener, ActionListener {

    Statement stmt = dbconnect.getStatementvalue();
    Connection con = dbconnect.getConnectionvalue();
    public static JTable table; // The table for displaying data
    public static JScrollPane scrollPane;
    public static JPanel mainpanel, panel, panel1;
    public static JButton button;
    DeptTableModel depttm;

    public DeptFrame() throws SQLException {
        super("The Masters: Department");
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    con.close();
                } catch (SQLException sqle) {
                    System.out.println("windowClosing" + sqle);
                }
                System.exit(0);
            }
        }
        );

        ResultSet rstable = getContentsOfTable();
        depttm = new DeptTableModel(rstable);

        table = new JTable(); // Displays the table
        table.setModel(depttm);
        table.setForeground(Color.gray);
        table.setBackground(Color.ORANGE);
        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(false);
        table.setSize(300, 300);
        scrollPane = new JScrollPane(table);

        button = new JButton("ViewReport");

        button.addActionListener(this);
        mainpanel = new JPanel();

        panel1 = new JPanel();

        panel1.add(button);
        mainpanel.setLayout(new BorderLayout());
        mainpanel.add(scrollPane);
        mainpanel.add("South", panel1);
    }

    /**
     * @param args * @throws SQLException
     */
    public static void main(String[] args)
            throws SQLException {
        DeptFrame df = new DeptFrame();
        df.add(mainpanel);
        df.setSize(700, 700);
        df.getContentPane().add(mainpanel);
        df.setVisible(true);
    }

    public ResultSet getContentsOfTable() throws SQLException {
        ResultSet rs = null;
        try {
            rs = stmt.executeQuery("select * from M_department");
        } catch (SQLException e) {
            System.out.println("Query" + e);
        }
        return rs;
    }

    @Override
    public void cursorMoved(RowSetEvent arg0) {
    }

    @Override
    public void rowChanged(RowSetEvent arg0) {
    }

    @Override
    public void rowSetChanged(RowSetEvent event) {
    }

    @Override
    public void actionPerformed(ActionEvent e) {         // TODO Auto-generated method stub         String action =
        e.getActionCommand();
        if (action.equals("ViewReport")) {
            String[] args = null;
            TESTJASPER.main(args);
            try {
                TESTJASPER.openPdf();
            } catch (IOException e1) {             // TODO
                Auto - generated catch block e1.printStackTrace();
            } catch
                    (InterruptedException e1) {             // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
}

这里我实现了表模型侦听器并设置 JTable 值

package org.table.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.RowSet;
import javax.sql.RowSetListener;
import javax.sql.rowset.CachedRowSet;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import oracle.jdbc.rowset.OracleCachedRowSet;
import org.connect.dbconnect;
import org.frames.src.DeptFrame;

public class DeptTableModel implements TableModel {
    Statement stmt = dbconnect.getStatementvalue();
    Connection con = dbconnect.getConnectionvalue();
    static ResultSet rsdept;
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows;
    public OracleCachedRowSet ocrs;

    public ResultSet getDeptRowSet() {
        return rsdept;
    }

    public DeptTableModel(ResultSet rsarg) throws SQLException {
        this.rsdept = rsarg;
        this.metadata = this.rsdept.getMetaData();
        this.numcols = metadata.getColumnCount();
        ocrs = new OracleCachedRowSet();
        ocrs.populate(this.rsdept);
        ocrs.beforeFirst();
        this.numrows = 0;
        while (ocrs.next()) {
            this.numrows++;
        }
        ocrs.beforeFirst();
        //System.out.println(numrows);      //System.out.println(numcols);  }

    public void close() {
        try {
            rsdept.getStatement().close();
        } catch (SQLException e) {
            System.out.print(e);
        }
    }

    /**
     * Automatically close when we're garbage collected
     */
    protected void finalize() {
        close();
    }

    @Override
    public void addTableModelListener(TableModelListener arg0) {         // TODO Auto - generated method stub
    }

    @Override
    public Class
    getColumnClass(int column) {
        return String.class;
    }

    @Override
    public int getColumnCount() {
        return numcols;
    }

    @Override
    public String
    getColumnName(int column) {
        try {
            return this.metadata.getColumnLabel(column + 1);
        } catch (SQLException e) {
            return e.toString();
        }
    }

    @Override
    public int getRowCount() {
        return numrows;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        try {
            ocrs.absolute(rowIndex + 1);
            Object o = ocrs.getObject(columnIndex + 1);
            if (o == null)
                return null;
            else
                return o.toString();
        } catch (SQLException e) {
            System.out.print(e);
            return e.toString();
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void
    removeTableModelListener(TableModelListener arg0) {         // TODO Auto - generated method stub
    }

    @Override
    public void setValueAt(Object value, int row, int column) {
        System.out.println("Calling setValueAt row " + row + ", column " + column + " value is" + value.toString());

        System.out.println(getColumnName(column));
        System.out.println(getValueAt(row, 0));
        String updateq = "update M_department set " + getColumnName(column) + "='" + value.toString()
                + "' where code = '" + getValueAt(row, 0) + "' ";
        System.out.println(updateq);
        try {
            stmt.executeUpdate(updateq);
            DeptFrame x = new DeptFrame();
            new DeptTableModel(x.getContentsOfTable());
        } catch (SQLException e) {             // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Error" + e);
        }
    }
}

一切工作正常,但更新一行后我的 jtable 没有刷新

Here i connect my database:

package org.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class dbconnect {

    public static Connection getConnectionvalue() {
        Statement stmt = null;
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            con = DriverManager.getConnection(url, "system", "kingdom");
            con.setAutoCommit(true);
        } catch (Exception e) {
            System.out.println("Connection Error" + e);
        }
        return con;
    }

    public static Statement
    getStatementvalue() {
        Statement stmt = null;
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            con = DriverManager.getConnection(url, "system", "kingdom");
            con.setAutoCommit(true);
            stmt = con.createStatement();
        } catch (Exception e) {
            System.out.println("Connection Error" + e);
        }
        return stmt;
    }
}

Here i created the frame and getting the database table values. And then i passed the resultset of table values to the Deptmodeltable

package org.frames.src;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.connect.dbconnect;
import org.reports.master.TESTJASPER;
import org.table.model.DeptTableModel;

import java.awt.event.ActionListener;
import java.io.IOException;

public class DeptFrame extends JFrame implements RowSetListener, ActionListener {

    Statement stmt = dbconnect.getStatementvalue();
    Connection con = dbconnect.getConnectionvalue();
    public static JTable table; // The table for displaying data
    public static JScrollPane scrollPane;
    public static JPanel mainpanel, panel, panel1;
    public static JButton button;
    DeptTableModel depttm;

    public DeptFrame() throws SQLException {
        super("The Masters: Department");
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    con.close();
                } catch (SQLException sqle) {
                    System.out.println("windowClosing" + sqle);
                }
                System.exit(0);
            }
        }
        );

        ResultSet rstable = getContentsOfTable();
        depttm = new DeptTableModel(rstable);

        table = new JTable(); // Displays the table
        table.setModel(depttm);
        table.setForeground(Color.gray);
        table.setBackground(Color.ORANGE);
        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(false);
        table.setSize(300, 300);
        scrollPane = new JScrollPane(table);

        button = new JButton("ViewReport");

        button.addActionListener(this);
        mainpanel = new JPanel();

        panel1 = new JPanel();

        panel1.add(button);
        mainpanel.setLayout(new BorderLayout());
        mainpanel.add(scrollPane);
        mainpanel.add("South", panel1);
    }

    /**
     * @param args * @throws SQLException
     */
    public static void main(String[] args)
            throws SQLException {
        DeptFrame df = new DeptFrame();
        df.add(mainpanel);
        df.setSize(700, 700);
        df.getContentPane().add(mainpanel);
        df.setVisible(true);
    }

    public ResultSet getContentsOfTable() throws SQLException {
        ResultSet rs = null;
        try {
            rs = stmt.executeQuery("select * from M_department");
        } catch (SQLException e) {
            System.out.println("Query" + e);
        }
        return rs;
    }

    @Override
    public void cursorMoved(RowSetEvent arg0) {
    }

    @Override
    public void rowChanged(RowSetEvent arg0) {
    }

    @Override
    public void rowSetChanged(RowSetEvent event) {
    }

    @Override
    public void actionPerformed(ActionEvent e) {         // TODO Auto-generated method stub         String action =
        e.getActionCommand();
        if (action.equals("ViewReport")) {
            String[] args = null;
            TESTJASPER.main(args);
            try {
                TESTJASPER.openPdf();
            } catch (IOException e1) {             // TODO
                Auto - generated catch block e1.printStackTrace();
            } catch
                    (InterruptedException e1) {             // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
}

Here i implements the table model listener and setting the JTable values

package org.table.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.RowSet;
import javax.sql.RowSetListener;
import javax.sql.rowset.CachedRowSet;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import oracle.jdbc.rowset.OracleCachedRowSet;
import org.connect.dbconnect;
import org.frames.src.DeptFrame;

public class DeptTableModel implements TableModel {
    Statement stmt = dbconnect.getStatementvalue();
    Connection con = dbconnect.getConnectionvalue();
    static ResultSet rsdept;
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows;
    public OracleCachedRowSet ocrs;

    public ResultSet getDeptRowSet() {
        return rsdept;
    }

    public DeptTableModel(ResultSet rsarg) throws SQLException {
        this.rsdept = rsarg;
        this.metadata = this.rsdept.getMetaData();
        this.numcols = metadata.getColumnCount();
        ocrs = new OracleCachedRowSet();
        ocrs.populate(this.rsdept);
        ocrs.beforeFirst();
        this.numrows = 0;
        while (ocrs.next()) {
            this.numrows++;
        }
        ocrs.beforeFirst();
        //System.out.println(numrows);      //System.out.println(numcols);  }

    public void close() {
        try {
            rsdept.getStatement().close();
        } catch (SQLException e) {
            System.out.print(e);
        }
    }

    /**
     * Automatically close when we're garbage collected
     */
    protected void finalize() {
        close();
    }

    @Override
    public void addTableModelListener(TableModelListener arg0) {         // TODO Auto - generated method stub
    }

    @Override
    public Class
    getColumnClass(int column) {
        return String.class;
    }

    @Override
    public int getColumnCount() {
        return numcols;
    }

    @Override
    public String
    getColumnName(int column) {
        try {
            return this.metadata.getColumnLabel(column + 1);
        } catch (SQLException e) {
            return e.toString();
        }
    }

    @Override
    public int getRowCount() {
        return numrows;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        try {
            ocrs.absolute(rowIndex + 1);
            Object o = ocrs.getObject(columnIndex + 1);
            if (o == null)
                return null;
            else
                return o.toString();
        } catch (SQLException e) {
            System.out.print(e);
            return e.toString();
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void
    removeTableModelListener(TableModelListener arg0) {         // TODO Auto - generated method stub
    }

    @Override
    public void setValueAt(Object value, int row, int column) {
        System.out.println("Calling setValueAt row " + row + ", column " + column + " value is" + value.toString());

        System.out.println(getColumnName(column));
        System.out.println(getValueAt(row, 0));
        String updateq = "update M_department set " + getColumnName(column) + "='" + value.toString()
                + "' where code = '" + getValueAt(row, 0) + "' ";
        System.out.println(updateq);
        try {
            stmt.executeUpdate(updateq);
            DeptFrame x = new DeptFrame();
            new DeptTableModel(x.getContentsOfTable());
        } catch (SQLException e) {             // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Error" + e);
        }
    }
}

Everything works fine, but my jtable not getting refreshed after updating a row

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦过后 2025-01-11 20:28:39

您在底部附近

  stmt.executeUpdate(updateq);  
  DeptFrame x=new DeptFrame();   
  new DeptTableModel(x.getContentsOfTable());  

1) 我看到一个 stmt.executeUpdate 调用,但我没有看到任何 commit 调用。你开启了自动提交吗?我认为甲骨文默认情况下关闭了该功能,因此正在执行,但是新的框架+模型具有旧内容,因为新内容从未提交?

2)为什么你要创建*另一个没有引用的DeptTableModel?看起来 DeptFrame 已经在内部创建了一个,那么第二个是做什么用的呢?

you have near the bottom bottom

  stmt.executeUpdate(updateq);  
  DeptFrame x=new DeptFrame();   
  new DeptTableModel(x.getContentsOfTable());  

1) I see a stmt.executeUpdate call, but i dont' see any commit calls. do you have autocommit turned on? i thought oracle had that off by default, so the execute is occuring, but then the new frame+model has the old content because the new content isnever committed?

2) why are you creating *yet another DeptTableModel with no references there? it looks like DeptFrame is already creating one internally, so what's this second one for?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文