Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8247633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T22:54:53+00:00 2026-06-07T22:54:53+00:00

I’ve a requirement where, based on the content of a HashMap<String, String> , I’ve

  • 0

I’ve a requirement where, based on the content of a HashMap<String, String>, I’ve to add/remove columns from my table. While I’m able to add/remove columns, but my problem is that for some reason when I create new columns, the values are not getting set in the respective columns. I’m unable to figure out why.

Posting an SSCCE for your reference. Can you please tell me what am I doing wrong?

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T22:54:54+00:00Added an answer on June 7, 2026 at 10:54 pm

    That’s a lot of code to update a table. Try updating the model. Table will re-render itself. I had to change one further line:

    infoTable.setAutoCreateColumnsFromModel(true);

    And, Hashmap is not a good fit for the model data. How do I easily get the value at say row 3, column 2 from a HashMap?

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
Does anyone know how can I replace this 2 symbol below from the string
I am currently running into a problem where an element is coming back from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
I've got a string that has curly quotes in it. I'd like to replace
Specifically, suppose I start with the string string =hello \'i am \' me And

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.