2012-05-01 65 views
2

我正在製作一個與圖形相關的程序,所以我需要動態創建/刪除JTable中的列以模擬鄰接表。我已經可以在需要時創建列,但無法刪除它們,因爲如果我刪除一列然後再創建另一列,則以前的數據(來自已刪除的列)將顯示在最新的列中。刪除JTable中的列

我讀過這是因爲列數據不會從tablemodel中刪除。我看過一些示例來隱藏或顯示列,但我需要真正刪除它們,然後當我得到二維數據矩陣時,我沒有交叉引用或不良數據。

第一校正:

private DefaultTableModel removeCol(int id){ 
     DefaultTableModel tmp = new DefaultTableModel(); 
     int columnas = modelo.getColumnCount(); 
     for(int i=0;i<columnas;i++){ 
      if(i!=id) 
       tmp.addColumn(modelo.getColumnName(i)); 
     } 
     int rows = modelo.getRowCount(); 
     String datos[] = new String[columnas-1]; 
     for(int row=0;row<rows;row++){ 
      for(int col=0,sel=0;col<columnas;col++,sel++){ 
       if(col!=id) 
        datos[sel] = (String) modelo.getValueAt(row, col); 
       else 
        sel--; 
      } 
      tmp.addRow(datos); 
     } 
     return tmp; 

    } 

當調用:

DefaultTableModel mo = removeCol(i); 
    tblTrans = new JTable(mo); 
+3

一種方法是提供一個新的'TableModel'與除了少一列以外的相同數據。也許更好的方法是創建一個定製表模型,它允許您配置列的可見性並在運行時調整'columnCount'和相關列。 –

+0

我試着做第一個選項,但得到一個更正後的TableModel(使用調試器檢查數據,列和所有內容都是正確的)我無法讓JTable顯示新模型,它顯示舊模型:S(詳情請參閱我的文章) –

+0

欲瞭解更快的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

4

adjacency matrix可在AbstractTableModel,在這裏可以明確地操縱各行更容易地操縱以的Elid一列。概括地說,

class MatrixModel extends AbstractTableModel { 

    private int rows; 
    private int cols; 
    private Boolean[][] matrix; 

    MatrixModel(int rows, int cols) { 
     this.rows = rows; 
     this.cols = cols; 
     matrix = new Boolean[rows][cols]; 
    } 

    public void deleteColumn(int col) { 
     for (Boolean[] row : matrix) { 
      Boolean[] newRow = new Boolean[row.length - 1]; 
      // TODO: copy remaining values 
      row = newRow; 
     } 
     this.fireTableStructureChanged(); 
    } 
    ... 
} 
2

例如

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Stack; 
import javax.swing.JButton; 
import javax.swing.JDialog; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.table.TableColumn; 

public class MyDialog extends JDialog { 

    private static final long serialVersionUID = 1L; 
    private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; 
    private Stack<TableColumn> colDeleted = new Stack<TableColumn>(); 

    public MyDialog() { 
     Object[][] data = {{"Mary", "Campione", "Snowboarding", new Integer(5), false}, 
      {"Alison", "Huml", "Rowing", new Integer(3), true}, 
      {"Kathy", "Walrath", "Knitting", new Integer(2), false}, 
      {"Sharon", "Zakhour", "Speed reading", new Integer(20), true}, 
      {"Philip", "Milne", "Pool", new Integer(10), false}}; 
     final JTable table = new javax.swing.JTable(data, columnNames); 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     add(new JScrollPane(table)); 
     final JButton button1 = new JButton("Add Col"); 
     final JButton button = new JButton("Remove Last Col"); 
     button.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent arg0) { 
       if (table.getColumnCount() > 0) { 
        TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1); 
        table.removeColumn(colToDelete); 
        table.validate(); 
        colDeleted.push(colToDelete); 
        button1.setEnabled(true); 
       } else { 
        button.setEnabled(false); 
       } 
      } 
     }); 
     button1.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent arg0) { 
       if (colDeleted.size() > 0) { 
        table.addColumn(colDeleted.pop()); 
        table.validate(); 
        button.setEnabled(true); 
       } else { 
        button1.setEnabled(false); 
       } 
      } 
     }); 
     JPanel southPanel = new JPanel(); 
     southPanel.add(button); 
     southPanel.add(button1); 
     add(southPanel, BorderLayout.SOUTH); 
     setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
     pack(); 
     setLocation(150, 150); 
     setVisible(true); 
    } 

    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       MyDialog myDialog = new MyDialog(); 
      } 
     }); 
    } 
} 
0

因爲DefaultModelTable沒有removeColumn該代碼可用於:

private String[] getRemainingIdentifiers(int columnIndex) { 

    String[] identifiers = new String[table.getColumnCount() - 1]; 
    int k = 0; 

    for(int i = 0; i < table.getColumnCount(); i++) { 
     if(i != columnIndex) { 
      identifiers[k++] = table.getColumnName(i); 
     } 
    } 

    return identifiers; 
} 

private void removeColumn(int columnIndex) { 

    String[][] data = new String[table.getRowCount()][table.getColumnCount() - 1]; 

    for(int i = 0; i < table.getRowCount(); i++) { 
     for(int j = 0; j < table.getColumnCount(); j++) { 

      if(j != columnIndex) { 
       if(table.getValueAt(i, j) == null) { 
        table.setValueAt("", i, j); 
       } 
       if(j < columnIndex) { 
        data[i][j] = table.getValueAt(i, j).toString(); 
       } else { 
        data[i][j - 1] = table.getValueAt(i, j).toString(); 
       } 
      } 
     } 
    } 

    modeltable = new DefaultTableModel(data, getRemainingIdentifiers(columnIndex)); 
    table.setModel(modeltable); 

} 
0

的DefaultDataModel沒有一個真正removeColumn()函數,所以我自己寫了一個函數,可以真正解決問題。

private void removeColumn(int index, JTable myTable){ 
    int nRow= myTable.getRowCount(); 
    int nCol= myTable.getColumnCount()-1; 
    Object[][] cells= new Object[nRow][nCol]; 
    String[] names= new String[nCol]; 

    for(int j=0; j<nCol; j++){ 
     if(j<index){ 
      names[j]= myTable.getColumnName(j); 
      for(int i=0; i<nRow; i++){ 
       cells[i][j]= myTable.getValueAt(i, j); 
      } 
     }else{ 
      names[j]= myTable.getColumnName(j+1); 
      for(int i=0; i<nRow; i++){ 
       cells[i][j]= myTable.getValueAt(i, j+1); 
      } 
     } 
    } 

    DefaultTableModel newModel= new DefaultTableModel(cells, names); 
    myTable.setModel(newModel);  
} 
+0

請不要簡單地在多個問題上發佈相同的答案,至少不能解釋它對每個問題的適用性。 –