JTable动态更新

时间:2012-04-19 01:15:30

标签: java swing jtable jframe

我有一个正在进行的项目,它允许我创建模板和输入数据。有一点不起作用的是该表不是动态更新的。一旦我关闭应用程序并再次运行它,它只会刷新。是否有类似于UpdateUI的方法,它在您面前更新而无需退出应用程序并再次重新打开以查看更改?我有下面的代码,有人可以指出什么代码以及我将它放在课堂上的位置?谢谢。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;


public class ViewTable extends JFrame {

    private static final long serialVersionUID = 1L;
    private static final String PREFERRED_LOOK_AND_FEEL = null;
    private static String tableName;
    private String[] columnNames;
    private String[][] data;
    private JPanel mainPanel;
    private JTable tablePane;
    private int dataX;
    private int dataY;

    public ViewTable(String tableName){
        this.tableName=tableName;

        initComponents();
        loadDB();
        displayTable();

        /*setDefaultCloseOperation(CreateTemplate.DISPOSE_ON_CLOSE);
        setSize(700,700);
        setTitle("View Table");
        setVisible(true);*/
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setSize(dim.width, dim.height);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);


    }

    private void initComponents() {
        mainPanel = new JPanel(new BorderLayout());
        this.add(mainPanel);
        mainPanel.setBackground(Color.gray);

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(Color.DARK_GRAY);
        mainPanel.add(topPanel,BorderLayout.NORTH);

        JLabel titleLabel = new JLabel(this.tableName);
        titleLabel.setBorder(new LineBorder(Color.black));
        titleLabel.setFont(new Font("Helvetica", Font.BOLD, 24));
        titleLabel.setForeground(Color.white);
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        topPanel.add(titleLabel,BorderLayout.CENTER);


        JPanel buttonPanel = new JPanel(new BorderLayout());
        JButton exitButton = new JButton("Finish");
        exitButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                close_window();
            }
        });
        exitButton.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
        buttonPanel.add(exitButton,BorderLayout.EAST);

        JButton deleteButton = new JButton("Delete Entry");
        deleteButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                Object[] rows = new Object[dataX-1];
                for (int r=0;r!=rows.length;r++){
                    rows[r] = data[r][0];
                }
                //JOptionPane delAsk = new JOptionPane("Delete entry:",JOptionPane.PLAIN_MESSAGE,JOptionPane.DEFAULT_OPTION,null,rows,rows[0]);
                //delAsk.
                //delAsk.set.InputDialogue(null,"Delete entry:","Delete",JOptionPane.PLAIN_MESSAGE,null,rows,rows[0]);
                //JDialog dialog = delAsk.createDialog(null, "Delete");
                //dialog.show();
                //String del = (String)delAsk.getInputValue();
                //System.out.println(del);

                Object deleteRow 
                = JOptionPane.showInputDialog(null,"Which entry do you wish to delete",
                        "Delete Entry",JOptionPane.INFORMATION_MESSAGE,null,
                        rows,rows[0]);      
                int index = -1;
                for(int i=0;i!=rows.length;i++){
                    if(rows[i].equals(deleteRow.toString())){ index = i; }
                }

                SQLCommands.SQLCommand("DELETE FROM "+tableName+" WHERE recID='"+index+"'");
                initComponents();
                loadDB();
                displayTable();
                tablePane.updateUI();
            }
        });
        deleteButton.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
        buttonPanel.add(deleteButton,BorderLayout.WEST);

        topPanel.add(buttonPanel,BorderLayout.EAST);

    }

    private void close_window(){ this.dispose(); }

    private void loadDB(){
        //get column names
        columnNames = getColumnNames();

        for (String S : columnNames){ System.out.println(S); }//JOptionPane.showInputDialog("Enter template name"); }

        //Temp add new dummy data
        //SQLCommands.SQLCommand("INSERT INTO "+tableName+" VALUES (1,'av', 'bv', 'cv', 'dv', 'ev')");



        //use column names to populate data

        String[] col = SQLCommands.returnSQLCommand("SELECT "+columnNames[0]+" FROM "+tableName+"");

        dataX = col.length+1;
        dataY = columnNames.length;
        System.out.println(dataX+" "+dataY);

        data = new String[dataX][dataY];
        printTable(data);
        System.out.println();

        //e.g. data[4][0] => "SELECT Name FROM tableName"[4]

        for(int j=0;j!=columnNames.length;j++){
            String n = columnNames[j];

            col = SQLCommands.returnSQLCommand("SELECT "+n+" FROM "+tableName+"");

            for(int i=0; i!=col.length; i++){
                data[i][j]=col[i];
            }
        }
        for(int j=0;j!=dataY;j++){
            data[dataX-1][j]="";
        }

        for(String D1[] : data){
            for(String D : D1){
                System.out.print(D+" ");
            }
            System.out.printf("\n");
        }

        /*columnNames = new String[2];
        columnNames[0] = "col 1";
        columnNames[1] = "col 2";
        data = new String[2][2];
        data[0][0] = "hello";
        data[0][1] = "good bye";
        dataX = 2;
        dataY = 2;*/
    }

    private void displayTable(){
        //use JTable
        tablePane = new JTable(data,columnNames);
        tablePane.setFillsViewportHeight(true);
        tablePane.setShowHorizontalLines(true);

        tablePane.setCellSelectionEnabled(true);
        tablePane.setRowSelectionAllowed(true);



        tablePane.getDefaultEditor(String.class).addCellEditorListener(new MyCellEditorListener(tablePane));

        //new JScrollPane which uses the table
        JScrollPane scrollPane = new JScrollPane(tablePane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBorder(new EmptyBorder(new Insets(15,15,15,15)));

        //put JScrollpane in CENTER box
        mainPanel.add(scrollPane,BorderLayout.CENTER);

    }

    public static String[] getColumnNames(){
        Connection connection=null;
        Statement statement=null;
        ResultSet result = null;
        String[] names=null;

        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager
                    .getConnection("jdbc:sqlite:Media.db");
            statement = connection.createStatement();
            result = statement.executeQuery("PRAGMA table_info( "+tableName+" );");
            ArrayList<String> nameList = new ArrayList<String>();
            while(result.next()){
                nameList.add(result.getString(2));
            }
            names = new String[nameList.toArray().length-1];
            for (int i=1; i!=nameList.toArray().length; i++){
                names[i-1] = (String)nameList.toArray()[i];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return names;
    }

    private class MyCellEditorListener implements CellEditorListener
    {

        private JTable table;
        private String[][] datain;

        public MyCellEditorListener(JTable table){
            this.table = table;

            setupDataIn();


        }

        private void setupDataIn(){
            datain = new String[dataX][dataY];
            for(int i=0; i!=dataX; i++){
                for(int j=0; j!=dataY; j++){
                    datain[i][j]=data[i][j];
                }
            }
        }

        @Override
        public void editingCanceled(ChangeEvent arg0) {
            //Do Nothing
        }

        @Override
        public void editingStopped(ChangeEvent e) {
            // Update DB
            printTable(data);
            printTable(datain);

            for(int i=0; i!=dataX; i++){
                for(int j=0; j!=dataY; j++){
                    if(datain[i][j].equals(data[i][j])){
                        //DO Nothing
                    } else {
                        //Update or add new field
                        if(i==dataX-1){
                            System.out.println("new field");
                            String com = "INSERT INTO "+tableName+" VALUES ("+(dataX-1)+", ";
                            for(int y=0;y!=dataY;y++){
                                if(y==j){
                                    com += "'"+data[i][j]+"', ";
                                } else {
                                    com += "'', ";
                                }
                            }
                            com = com.substring(0, com.length()-2);
                            com+=")";

                            System.out.println(com);
                            SQLCommands.SQLCommand(com);
                            initComponents();
                            loadDB();
                            setupDataIn();
                            displayTable();
                            tablePane.updateUI();
                            break;

                        } else {
                            System.out.println("UPDATE "+tableName+" SET "+columnNames[j]+"='"+data[i][j]+"' WHERE recID="+i);
                            SQLCommands.SQLCommand("UPDATE "+tableName+" SET "+columnNames[j]+"='"+data[i][j]+"' WHERE recID="+i);
                        }
                    }
                }
            }

        }

    }

    private void printTable(String[][] t){
        for(String[] a : t){
            for(String b: a){
                System.out.print(b+" ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args){
        String [] tableNames = SQLCommands.returnSQLCommand("SELECT name FROM sqlite_master");
        new ViewTable(tableNames[tableNames.length -1]);
    }

}

1 个答案:

答案 0 :(得分:5)

您应该使用TableModel。结帐How to Use Tables。然后fireTableDataChanged()(或另一个适当的fire *方法)会通知您的表格有关更改。

也许Using JDBC with GUI API可能会有所帮助。它演示了JDBC和JTable的非常基本的集成。