可编辑的JTable

时间:2015-08-12 08:34:13

标签: java sql swing jtable

我有一个JTable,我用SQL Query来填充。我也使单元格可编辑我编辑的任何单元格都没有被保存,它只是恢复到我完成编辑后的状态。

我不完全确定使JTable完全可编辑的正确方法是什么,任何正在更新的单元都将保存在JTable本身上,并将在SQL数据库上更新。

我想我应该使用带有fireTableCellUpdated的TableModelListener,但我无法让它工作。

这是用于显示JTable的代码

import java.sql.*;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import java.awt.Dimension;
import java.awt.event.*;
import java.util.*;

@SuppressWarnings("serial")
public class Test_Table extends JPanel {
    //Load Componenets
    JTable table;
    static TableModel dataModel;
    static Connection conn;
    static Statement stmt;  
    static Vector<Vector<String>> resultVector=new Vector<Vector<String>>();
    static Vector<String> fieldVector=new Vector<String>();
    String[] col_name = {"A","B","C","D","E","F","G"};


    //Get Data from SQL Database
    public static void getTableData(Vector<Vector<String>>resultVector, Vector<String>fieldVector) throws SQLException {
        fieldVector.clear();
        resultVector.clear();
        int colCount;
        String query="SELECT *FROM test_table WHERE DATE(time_stamp)=CURDATE() ORDER BY time_stamp DESC";
        ResultSet result;
        result=stmt.executeQuery(query);
        ResultSetMetaData metaData=result.getMetaData();
        colCount=metaData.getColumnCount();
        for (int i=0; i<colCount; i++)
            fieldVector.add(metaData.getCatalogName(i+1));
        for (int i=0; result.next(); i++) {
            resultVector.add(new Vector<String>());
        for (int j=0; j<colCount; j++)
            resultVector.get(i).add(result.getString(j+1));
        }
    }

    public Test_Table() throws SQLException, ClassNotFoundException {

        //Connection to the SQL Database
        Class.forName("com.mysql.jdbc.Driver");
          final String url = "jdbc:mysql://localhost:3306/test_table";
          final String username = "";
          final String password = "";
        conn=DriverManager.getConnection(url, username, password);
        stmt=conn.createStatement();

        //Model to Create JTable filled with SQL Database
        getTableData(resultVector,fieldVector);
            dataModel=new AbstractTableModel(){
            public int getColumnCount() {return fieldVector.size();}
            public int getRowCount() {return resultVector.size();}
            public Object getValueAt(int row, int col) {
                return resultVector.get(row).get(col);
            }
               public boolean isCellEditable(int row, int col) {
                   return true;
                }


               public String getColumnName(int index) {
                return col_name[index];
            }

        };

        //Adds TableMode Listener
        dataModel.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                try {
                    tableModelTableChanged(e);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }

        });

        //Create JTable with Database and add to JPanel
        table=new JTable(dataModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setPreferredScrollableViewportSize(new Dimension(1500,400));
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        table.setDefaultRenderer(Object.class, centerRenderer);
        final JScrollPane scrollpane=new JScrollPane(table);
        add(scrollpane);
    }

    public void tableModelTableChanged(TableModelEvent evt) throws SQLException{
          ?????????
        }

    //Update JTable when new row Inserted
    public static void update_table() throws SQLException {
    getTableData(resultVector, fieldVector);
    ((AbstractTableModel) dataModel).fireTableDataChanged();
    }

    //Close SQL Connection
    static void close() throws SQLException {
        if (stmt!=null)stmt.close();
        if(conn!=null) conn.close();
    }



    public void processWindowEvenet(WindowEvent e) {
        if (e.getID()==WindowEvent.WINDOW_CLOSING) {
            try {
                Testing_Table.close();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
            System.exit(0);
        }
    }

    public static void main (String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, SQLException {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        JFrame frame=new JFrame();
        frame.add(new Testing_Table());
        frame.pack();
        frame.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:0)

TableModelEvent告诉您哪些数据已更改。您可以编写逻辑并制作适当的JDBC调用来更新数据库中的数据。

由于JTable中的数据已被用户更改。从DB中再次更新它没有意义。

是的,@ mKorbel是正确的,您应该在SwingWorker中执行此操作。但是要开始它可能更容易首先在tableModelTableChanged()方法中实现所有内容并在之后重构它。