从Java中的Hashtable填充JTable

时间:2008-11-15 07:41:36

标签: java swing hashtable jtable

我有一个从用户获取密钥并生成Hashtable的函数(在密钥指定的模式上)。在创建Hashtable之后,我想填充一个JTable,以便每个列代表一个键,每行代表与键相关的值。我尝试了一切,但无法完成这项工作。我不是在构造函数中创建表,因为我需要从用户那里获得输入。

2 个答案:

答案 0 :(得分:2)

请参阅How to Use Tables: Creating a Table Model

  

使用的JTable构造函数   SimpleTableDemo创建其表   模型的代码如下:

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);
    }
}

您基本上必须以上述方式包装哈希表。这是一个例子。

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() {
        super();
        initialize();
        m_hash = new Hashtable<String, String>();
        m_hash.put("Dog", "Bow");
    }

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

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        this.setSize(409, 290);
        this.setTitle("JFrame");
        this.setContentPane(getJContentPane());
    }

    /**
     * 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();
            m_scrollPane.setViewportView(getM_table());
        }
        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) {
                    onButtonPressed();
                }
            });
        }
        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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }
}  //  @jve:decl-index=0:visual-constraint="10,10"

答案 1 :(得分:1)

首先,避免Hashtable,直接进入Map。在这种情况下,您可能需要两种可能的标准实现:LinkedHashMap可以保留添加条目的顺序; TreeMapSortedMap / NavigableMap会对结果进行排序(顺序可以由Comparator确定。或者您可能想要一种Map形式引发事件或提供TableModel

如果您希望从Map进行一次性转换,那么它非常简单。

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;
}

然后使用此预先填充的模型创建JTable

(免责声明:我没有测试或编译此代码。)

保持MapTableModel同步更多代码。一般来说,最好尽量避免重复国家。编写一个将自己公开为MapTableModel的类。你可以通过Map触发事件和TableModel调整Map来更加不相交(尽管注意Map没有基于索引的随机访问权限,所以对于大型地图,你需要聪明或缓慢。

另一方面,更简单的方法是将数据直接添加到DefaultTableModel,而不是使用Map