Populate JTable from a Hashtable in Java

I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.

Asked by: Freddie145 | Posted: 23-01-2022

Answer 1

See How to Use Tables: Creating a Table Model.

The JTable constructor used by SimpleTableDemo creates its table model with code like this:

new AbstractTableModel() {
    public String getColumnName(int col) {
        return columnNames[col].toString();
    public int getRowCount() { return rowData.length; }
    public int getColumnCount() { return columnNames.length; }
    public Object getValueAt(int row, int col) {
        return rowData[row][col];
    public boolean isCellEditable(int row, int col)
        { return true; }
    public void setValueAt(Object value, int row, int col) {
        rowData[row][col] = value;
        fireTableCellUpdated(row, col);

You basically have to wrap your hashtable in the above manner. Here's an example.

package eed3si9n.hashtabletable;

import java.awt.BorderLayout;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;
import java.awt.Dimension;

public class MainForm extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;  //  @jve:decl-index=0:visual-constraint="23,38"
    private JScrollPane m_scrollPane = null;
    private JTable m_table = null;
    private Hashtable<String, String> m_hash = null;
    private JButton m_btnAdd = null;    

     * This is the default constructor
    public MainForm() {
        m_hash = new Hashtable<String, String>();
        m_hash.put("Dog", "Bow");

    private void onButtonPressed() {
        m_hash.put("Cow", "Moo");

     * This method initializes this
     * @return void
    private void initialize() {
        this.setSize(409, 290);

     * This method initializes jContentPane
     * @return javax.swing.JPanel
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.setSize(new Dimension(500, 500));
            jContentPane.setPreferredSize(new Dimension(500, 500));
            jContentPane.add(getM_scrollPane(), BorderLayout.NORTH);
            jContentPane.add(getM_btnAdd(), BorderLayout.SOUTH);
        return jContentPane;

     * This method initializes m_scrollPane 
     * @return javax.swing.JScrollPane  
    private JScrollPane getM_scrollPane() {
        if (m_scrollPane == null) {
            m_scrollPane = new JScrollPane();
        return m_scrollPane;

     * This method initializes m_table  
     * @return javax.swing.JTable   
    private JTable getM_table() {
        if (m_table == null) {
            m_table = new JTable();
            m_table.setModel(new AbstractTableModel(){
    private static final long serialVersionUID = 1L;

    public int getColumnCount() {
        return 2;

    public int getRowCount() {
        return m_hash.size();

    public String getColumnName(int column) {
        if (column == 0) {
            return "Animal";
        } else {
            return "Sound";

    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return getKey(rowIndex);
        } else {
            return m_hash.get(getKey(rowIndex));
        } // if-else


    private String getKey(int a_index) {
        String retval = "";
        Enumeration<String> e = m_hash.keys();
        for (int i = 0; i < a_index + 1; i++) {
            retval = e.nextElement();
        } // for

        return retval;

        return m_table;

     * This method initializes m_btnAdd 
     * @return javax.swing.JButton  
    private JButton getM_btnAdd() {
        if (m_btnAdd == null) {
            m_btnAdd = new JButton();
            m_btnAdd.setPreferredSize(new Dimension(34, 30));
            m_btnAdd.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
        return m_btnAdd;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainForm frame = new MainForm();
                frame.setSize(500, 500);
}  //  @jve:decl-index=0:visual-constraint="10,10"

Answered by: Sienna900 | Posted: 24-02-2022

Answer 2

Firstly, avoid Hashtable, go straight for Map. In this case there two potential standard implementations you mights want: LinkedHashMap can retain the order that the entries were added; TreeMap, a SortedMap/NavigableMap, will sort the results (order of which can be determined by a Comparator. Alternatively you might want a form of Map that fire events or also provides a TableModel.

If you want a one time conversion from the Map to table, then it's pretty straightforward.

public static TableModel toTableModel(Map<?,?> map) {
    DefaultTableModel model = new DefaultTableModel(
        new Object[] { "Key", "Value" }, 0
    for (Map.Entry<?,?> entry : map) {
        model.addRow(new Object[] { entry.getKey(), entry.getValue() });
    return model;

Then just create the JTable with this pre-populated model.

(Disclaimer: I've not tested or so much as compiled this code.)

To keep the Map and TableModel synchronized is more code. Generally it's best to avoid duplicating state whereever possible. Write a class that exposes itself as both a Map and a TableModel. You could go more disjoint by having a Map that fires events and a TableModel that adapts the Map (although note that Map does not have random access based on index, so you'll need to be iether clever or slow for large maps).

Going the other way, a simpler approach would be to add the data straight to a DefaultTableModel and not using a Map at all.

Answered by: Melissa449 | Posted: 24-02-2022

Similar questions

Use Hashtable, Vector or HashMap or ArrayList in Java

One meme that gets stressed with Java development is always use ArrayList over Vector. Vector is deprecated. That may be true, but Vector and Hashtable have the advantage that they are synchronized. I am working with a heavily concurrent oriented application, wouldn't it benefit to use objects that are synchronized like Vector? It seems that they have their place?

java - Method to find Key in HashTable

I'm trying to create a method which iterates through a hashtable and returns the key as a string, whats the best way to go about this? EDIT: copied from comment Sorry if I didn't make it more clear, I'm trying to do this in Java. I've created a test class public void runprog() { hashMap.put("Butter", 50); hashMap.put("Beans", 40); for (Object o: hashMap.entrySet() ) { Map...

HashTable Java... Can you check my code

I'm writing an class for a hash table in java... can you please make sure that I am doing it correctly so far. I need to store StudentRecord objects in it.... I am calculating the hash value based on the student's ID which is of type long... package proj3; import java.util.LinkedList; public class HashTable { LinkedList&lt;StudentRecord&gt; [] buckets; int size; public HashTable(){ ...

java - Create Custom Hashtable

I need to create a Custom Hashtable extends java.lang.Hashtable and i need to override the get method to achieve the following behavior : if the key == null, it will return a new object of the type V if the super.get(key) == null, it will also return a new object of type V. Can anyone help me. I try to do this but I know it's wrong. import java.util.Hashtable; public ...

scope - Hashtable in java is giving me the last stored value, but not the right value

Sorry this is code is kind of long, but I needed to get the right scenario. Why does this code outputs all 'C''s? import java.util.Hashtable; public class Main { public static ContainsTheHash containsthehash = new ContainsTheHash(); public static StoresValues storesvalues = new StoresValues(); public static GetsValuesAndPrints getsvaluesandprints = new GetsValuesAndPr...

hashtable - What does it mean by "the hash table is open" in Java?

I was reading the Java api docs on Hashtable class and came across several questions. In the doc, it says "Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. " I tried the following code myself

java - Accesing a function via string stored in Hashtable

If I have function names stored as strings in a Hashtable. Is there a way to access the functions via the stored strings? EDIT I'm afraid the platform that i'm working on CLDC1.1/MIDP2.0 does not support Reflection. Any workaround possible?

java - How much memory does a Hashtable use?

In Java, if I create a Hashtable&lt;K, V&gt; and put N elements in it, how much memory will it occupy? If it's implementation dependent, what would be a good "guess"?

java - Update cached data in a hashtable

In order to minimize the number of database queries I need some sort of cache to store pairs of data. My approach now is a hashtable (with Strings as keys, Integers as value). But I want to be able to detect updates in the database and replace the values in my "cache". What I'm looking for is something that makes my stored pairs invalid after a preset timespan, perhaps 10-15 minutes. How would I implement that? Is there so...

Java Hashtable problem

I am having some problem with java hashtable. Following is my hastable key and values {corpus\2.txt=[cat sparrow], corpus\4.txt=[elephant sparrow], corpus\1.txt=[elephant cow], corpus\3.txt=[cow cat]} So if i want to access first tuple i have to pass key "corpus\2.txt" to get its value. If i pass value i can get it's key. But I want to make a function I pass like 1 2 3 4 etc. and get both key and value. An...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)