1

我有一个要求,根据 a 的内容HashMap<String, String>,我必须从表中添加/删除列。虽然我可以添加/删除列,但我的问题是,由于某种原因,当我创建新列时,没有在相应的列中设置值。我无法弄清楚为什么。

发布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
}
4

1 回答 1

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
}
于 2012-07-16T16:13:20.880 回答