Содержимое Jtable не будет обновляться после добавления данных в качестве параметра - PullRequest
3 голосов
/ 26 февраля 2010

У меня есть jtable, все работает нормально, если я устанавливаю данные таблицы как открытую переменную (не помещайте ее в параметр tablemodel). Но сейчас мне нужно установить данные таблицы в качестве параметра, и таблица не будет обновлять свое содержимое. Я распечатываю некоторое значение ячейки и номер строки, они оба обновлены и исправлены. Просто дисплей не изменился, все равно старое содержимое. Я пробовал все типы методов для обновления таблицы, включая fireTableDataChanged и перекрасить, и другие функции огня, ни одна из них не работает. Пожалуйста помоги. Большое спасибо !!!!!!

модель стола:

       public class MyTableModel extends AbstractTableModel {

           protected String[] columnNames;
           private String[][] data;


            public MyTableModel(String[] columnNames, String[][] data){
                this.columnNames = columnNames;
                this.data = data;
                //I add this here but it still doesn't refresh the table
                fireTableDataChanged();
            }

            public int getColumnCount() {
                return columnNames.length;
            }

            public int getRowCount() {
                return data.length;
            }

            public String getColumnName(int col) {
                return columnNames[col];
            }

            public String getValueAt(int row, int col) {
                return data[row][col];                  
            }

           public void setData(String[][] newdata) {   
              data = newdata;

              fireTableDataChanged();   
              }  
        }

Код, который я обновляю: модель таблицы и таблица:

        tableModel=new MyTableModel(columnNames, data);
        tableModel.fireTableDataChanged();
        table = new JTable();
        table.setModel(tableModel); 
        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
        //outputs showed the content is updated
        System.out.println("total row count" + table.getRowCount());
        System.out.println("cell info" + table.getValueAt(0,5));


        table.repaint();
        feedback.repaint();
        this.repaint();

Ответы [ 2 ]

8 голосов
/ 26 февраля 2010

Вы не должны переназначать свой стол:

 tableModel=new MyTableModel(columnNames, data);
 tableModel.fireTableDataChanged(); // not necessary
 table = new JTable(); // dont do this, you are removing your handle to the table in your view
 table.setModel(tableModel); 
1 голос
/ 08 июля 2010

Я сделал данные модели такими же статичными, как и все в порядке. Я не забочусь об OOPS для этой части ..

/******************Its a custom class for creating custom editors so plz comment unwanted code ********************************/

@SuppressWarnings("serial")
class MyTableModel extends AbstractTableModel 
{
    protected String[] columnNames = {"URL",
                                    "Category",
                                    "Select"};
    protected static Object data [][] = null;

    public MyTableModel() { 
     }

    public final Object[] longValues = {"http://www.oracle.com", "BOOK", Boolean.TRUE};

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {

        if(data !=null)
            return data.length;
        else
            return 0;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {

        if(data!=null)
            return data[row][col];
        else
            return null;
    }

    /*
     * JTable uses this method to determine the default renderer/
     * editor for each cell.  If we didn't implement this method,
     * then the last column would contain text ("true"/"false"),
     * rather than a check box.
     */
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    /*
     * Don't need to implement this method unless your table's
     * editable.
     */
    public boolean isCellEditable(int row, int col) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.
        if (col < 0) {
            return false;
        } else {
            return true;
        }
    }

    /*
     * Don't need to implement this method unless your table's
     * data can change.
     */
    public void setValueAt(Object value, int row, int col) 
    {

        data[row][col] = value;
        fireTableCellUpdated(row, col);
        // printDebugData();
    }

    private void printDebugData() {
        int numRows = getRowCount();
        int numCols = getColumnCount();

        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + data[i][j]);
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }
}

/***********************************/
//Use a Jbutton add a listener and put this code in it to test it works !!

Object d [][] = {
                {"http://www.abc.com", "ABC", new Boolean(false)},
                {"http://www.google.com", "DEF", new Boolean(true)},
                {"http://www.yahoo.com", "FGH", new Boolean(false)},
                {"http://www.google.com", "IJK", new Boolean(true)},
                {"http://www.yahoo.com", "LMN", new Boolean(false)}
            };

        model.data = d; //Important to update data
        model.fireTableDataChanged(); //Important to make changes reflected.
/*********************************************/
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...