2012-07-16 84 views
1

我有一個要求,其中基於HashMap<String, String>的內容,我必須從我的表中添加/刪除列。儘管我可以添加/刪除列,但是我的問題是,由於某些原因,當我創建新列時,值不會在相應的列中設置。我無法弄清楚爲什麼。JTable - 無法將值添加到新創建的列

發佈SSCCE供您參考。你能告訴我我做錯了什麼嗎?

import java.util.HashMap; 
import javax.swing.table.DefaultTableModel; 
import javax.swing.table.JTableHeader; 
import javax.swing.table.TableColumn; 
import javax.swing.table.TableColumnModel; 

public class TableTest extends javax.swing.JFrame { 

    /** 
    * Creates new form TableTest 
    */ 
    public TableTest() { 
     initComponents(); 
    } 

    private void resetTable(){ 
     TableColumnModel tableColumnModel = infoTable.getColumnModel(); 
     DefaultTableModel tableModel = (DefaultTableModel) infoTable.getModel(); 

     JTableHeader tableHeader = infoTable.getTableHeader(); 
     tableColumnModel.getColumn(0).setHeaderValue(""); 

     for(int columnIndex = 0; columnIndex < tableColumnModel.getColumnCount(); columnIndex++){ 
      if(columnIndex > 3){ 
       infoTable.removeColumn(tableColumnModel.getColumn(columnIndex)); 
      }else{ 
       tableModel.setValueAt("", 0, columnIndex); 
       tableModel.setValueAt("", 1, columnIndex); 
      } 
     } 

     tableHeader.repaint(); 
     infoTable.revalidate(); 
     infoTable.repaint(); 
    } 

    private void createTable(HashMap<String, String> parameterMap){ 

     resetTable(); 
     TableColumnModel tableColumnModel = infoTable.getColumnModel(); 
     DefaultTableModel tableModel = (DefaultTableModel) infoTable.getModel(); 

     if(!parameterMap.isEmpty()){ 
      int columnCount = 1; 
      for (String key : parameterMap.keySet()) { 
       if(columnCount >= tableColumnModel.getColumnCount()){ 
        tableModel.addColumn(""); 
        tableColumnModel.addColumn(new TableColumn()); 
       } 
       columnCount++; 
      } 
     } 
     infoTable.revalidate(); 
     infoTable.repaint(); 
    } 

    private void updateInformationTable(HashMap<String, String> parameterMap){ 

     createTable(parameterMap); 

     TableColumnModel tableColumnModel = infoTable.getColumnModel(); 
     DefaultTableModel tableModel = (DefaultTableModel) infoTable.getModel(); 

     JTableHeader tableHeader = infoTable.getTableHeader(); 

     if(!parameterMap.isEmpty()){ 
      tableColumnModel.getColumn(0).setHeaderValue(parameterMap.get("timer")); 

      int columnCount = 1; 
      for (String key : parameterMap.keySet()) { 

       tableModel.setValueAt((key.contains("unknown") ? "" : key), 0, columnCount); 
       tableModel.setValueAt(parameterMap.get(key), 1, columnCount); 
       columnCount++; 
      } 
     } 

     tableHeader.repaint(); 
     infoTable.revalidate(); 
     infoTable.repaint(); 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     jPanel1 = new javax.swing.JPanel(); 
     jScrollPane1 = new javax.swing.JScrollPane(); 
     infoTable = new javax.swing.JTable(); 
     jButton1 = new javax.swing.JButton(); 
     jButton2 = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     infoTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] { 
       {null, null, null, null}, 
       {null, null, null, null}, 
      }, 
      new String [] { 
       "Title 1", "", "", "" 
      } 
     )); 
     infoTable.setAutoscrolls(false); 
     infoTable.setShowHorizontalLines(false); 
     infoTable.setShowVerticalLines(false); 
     infoTable.setAutoCreateColumnsFromModel(false); 
     jScrollPane1.setViewportView(infoTable); 

     jButton1.setText("3 Columns"); 
     jButton1.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton1ActionPerformed(evt); 
      } 
     }); 

     jButton2.setText("5 Columns"); 
     jButton2.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton2ActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addComponent(jButton1) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 577, Short.MAX_VALUE) 
       .addComponent(jButton2)) 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() 
       .addContainerGap(243, Short.MAX_VALUE) 
       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(jButton1) 
        .addComponent(jButton2)) 
       .addContainerGap()) 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addGap(0, 25, Short.MAX_VALUE))) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 

     pack(); 
    }// </editor-fold> 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
     HashMap<String, String> map = new HashMap<String, String>(); 
     map.put("param1", "value1"); 
     map.put("param2", "value2"); 
     map.put("param3", "value3"); 

     updateInformationTable(map); 
    } 

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
     HashMap<String, String> map = new HashMap<String, String>(); 
     map.put("param1", "value1"); 
     map.put("param2", "value2"); 
     map.put("param3", "value3"); 
     map.put("param4", "value4"); 
     map.put("param5", "value5"); 

     updateInformationTable(map); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) { 
     /* 
     * Set the Nimbus look and feel 
     */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* 
     * If Nimbus (introduced in Java SE 6) is not available, stay with the 
     * default look and feel. For details see 
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel" /* 
        * UIManager.getSystemLookAndFeelClassName() 
        */); 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* 
     * Create and display the form 
     */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 

      public void run() { 
       new TableTest().setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify 
    private javax.swing.JTable infoTable; 
    private javax.swing.JButton jButton1; 
    private javax.swing.JButton jButton2; 
    private javax.swing.JPanel jPanel1; 
    private javax.swing.JScrollPane jScrollPane1; 
    // End of variables declaration 
} 

回答

1

這是一個很大的代碼更新表。嘗試更新模型。表格將重新呈現自己。我不得不改變一行:

infoTable.setAutoCreateColumnsFromModel(true);

而且,Hashmap不適合模型數據。我如何輕鬆地從HashMap獲得第3行第2列的值?

import java.util.HashMap; 
import java.util.Map; 

import javax.swing.table.DefaultTableModel; 

public class TableTest extends javax.swing.JFrame { 

    /** 
    * Creates new form TableTest 
    */ 
    public TableTest() { 
     initComponents(); 
    } 

    private void updateInformationTable(HashMap<String, String> parameterMap){ 

     infoTable.setModel(new MyTableModel(parameterMap)); 
    } 

    private class MyTableModel extends DefaultTableModel{ 

     private Map<String, String> data; 

     public MyTableModel(Map<String, String> data){ 
      this.data = data; 
     } 

     public int getRowCount() { 

      return 1; 
     } 

     public int getColumnCount() { 
      return data != null ? data.size() : 0; 
     } 

     public Object getValueAt(int rowIndex, int columnIndex) { 

      //FIXME : Return the value here 
      return rowIndex + "," + columnIndex; 
     } 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     jPanel1 = new javax.swing.JPanel(); 
     jScrollPane1 = new javax.swing.JScrollPane(); 
     infoTable = new javax.swing.JTable(); 
     jButton1 = new javax.swing.JButton(); 
     jButton2 = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     infoTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] { 
       {null, null, null, null}, 
       {null, null, null, null}, 
      }, 
      new String [] { 
       "Title 1", "", "", "" 
      } 
     )); 
     infoTable.setAutoscrolls(false); 
     infoTable.setShowHorizontalLines(false); 
     infoTable.setShowVerticalLines(false); 
     infoTable.setAutoCreateColumnsFromModel(true); 
     jScrollPane1.setViewportView(infoTable); 

     jButton1.setText("3 Columns"); 
     jButton1.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton1ActionPerformed(evt); 
      } 
     }); 

     jButton2.setText("5 Columns"); 
     jButton2.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton2ActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addComponent(jButton1) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 577, Short.MAX_VALUE) 
       .addComponent(jButton2)) 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() 
       .addContainerGap(243, Short.MAX_VALUE) 
       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(jButton1) 
        .addComponent(jButton2)) 
       .addContainerGap()) 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addGap(0, 25, Short.MAX_VALUE))) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 

     pack(); 
    }// </editor-fold> 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
     HashMap<String, String> map = new HashMap<String, String>(); 
     map.put("param1", "value1"); 
     map.put("param2", "value2"); 
     map.put("param3", "value3"); 

     updateInformationTable(map); 
    } 

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
     HashMap<String, String> map = new HashMap<String, String>(); 
     map.put("param1", "value1"); 
     map.put("param2", "value2"); 
     map.put("param3", "value3"); 
     map.put("param4", "value4"); 
     map.put("param5", "value5"); 

     updateInformationTable(map); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) { 
     /* 
     * Set the Nimbus look and feel 
     */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* 
     * If Nimbus (introduced in Java SE 6) is not available, stay with the 
     * default look and feel. For details see 
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel" /* 
        * UIManager.getSystemLookAndFeelClassName() 
        */); 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(TableTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* 
     * Create and display the form 
     */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 

      public void run() { 
       new TableTest().setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify 
    private javax.swing.JTable infoTable; 
    private javax.swing.JButton jButton1; 
    private javax.swing.JButton jButton2; 
    private javax.swing.JPanel jPanel1; 
    private javax.swing.JScrollPane jScrollPane1; 
    // End of variables declaration 
} 
+0

感謝您的回答! 「JTable」非常新穎,因此無知。我有一個HashMap,因爲在我的情況下,行數將被固定,即2.列的數量會有所不同,具體取決於我的地圖中的條目數量。第1行將包含來自映射的鍵,第2行將包含這些值。 – Sujay 2012-07-16 16:21:37