如何在Swing中打印HashMap?

时间:2014-05-25 13:39:51

标签: java swing jtable hashmap jlist

首先抱歉我的英语。我正在尝试构建一个程序,通过JOptionPane.showInputDialog()获取用户的输入并将其存储在HashMap<String, Integer>中。

我做到了并且有效。

但问题是我想在swing组件(HashMapJList或其他内容)中打印所有JTable键和值,但我不知道是哪个更好,更简单易用。 你有什么建议吗?


Masud 感谢您的回复,但我尝试了您的代码并且它给了我一个错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
     at java.util.Vector.elementAt(Unknown Source)
     at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)
     at javax.swing.JTable.setValueAt(Unknown Source)
     at Main.viewAll(Main.java:91)
     at Main$1.actionPerformed(Main.java:43)
     at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
     at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
     at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
     at java.awt.Component.processMouseEvent(Unknown Source)
     at javax.swing.JComponent.processMouseEvent(Unknown Source)
     at java.awt.Component.processEvent(Unknown Source)
     at java.awt.Container.processEvent(Unknown Source)
     at java.awt.Component.dispatchEventImpl(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Window.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
     at java.awt.EventQueue.access$200(Unknown Source)
     at java.awt.EventQueue$3.run(Unknown Source)
     at java.awt.EventQueue$3.run(Unknown Source)
     at java.security.AccessController.doPrivileged(Native Method)
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
     at java.awt.EventQueue$4.run(Unknown Source)
     at java.awt.EventQueue$4.run(Unknown Source)
     at java.security.AccessController.doPrivileged(Native Method)
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
     at java.awt.EventQueue.dispatchEvent(Unknown Source)
     at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.run(Unknown Source)

在错误中:第91行是我在for循环中写table.setValueAt(entry.getKey(), row, 0);的地方。第43行是我调用for循环的方法。

我试着解决它,但我什么都没解决。我刚看到当我使用HashMap给出的输入打印JOptionPane.showInputDialog()时出现此错误。如果我在代码中设置HashMap键和值,它就能完美运行。有什么想法解决它?

----------------------------------------------- --------------------------------------------

这是代码:

import java.awt.Container;

public class Main扩展JFrame {

static JTable table;
static JButton viewall, add, cercanome, cercamedia, esci;
static Map<String, Integer> registro = new HashMap<String, Integer>();

public static void main(String[] args) {

    JFrame f = new JFrame("Studenti");
    f.setSize(557, 597);
    f.setResizable(false);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    components(f.getContentPane());
}

public static void components(Container pane) {

    // Here i set all the components of the frame and i set up the ActionListeners for the buttons

    pane.setLayout(null);

    table = new JTable(registro.size(), 2);
    table.setBounds(10, 11, 384, 536);
    pane.add(table);

    viewall = new JButton("Visualizza Tutto");
    viewall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            viewAll();
        }
    });
    viewall.setBounds(404, 11, 130, 23);
    pane.add(viewall);

    add = new JButton("Aggiungi Alunno");
    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            addStudent();
        }
    });
    add.setBounds(404, 45, 130, 23);
    pane.add(add);

    cercanome = new JButton("Cerca per Nome");
    cercanome.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cercaNome();
        }
    });
    cercanome.setBounds(404, 79, 130, 23);
    pane.add(cercanome);

    cercamedia = new JButton("Cerca per Media");
    cercamedia.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cercaMedia();
        }
    });
    cercamedia.setBounds(404, 113, 130, 23);
    pane.add(cercamedia);

    esci = new JButton("Esci");
    esci.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    esci.setBounds(404, 147, 130, 23);
    pane.add(esci);

}

public static void viewAll() { // This is called when you press the button "viewall" to print the map.
    int row = 0;

    for(Map.Entry<String, Integer> entry : registro.entrySet()){
        table.setValueAt(entry.getKey(), row, 0);
        table.setValueAt(entry.getValue(), row, 1);
        row++;
    }
}

public static void addStudent() { // This is called when you click the button "add" to add elements to the map.
    registro.put(
            JOptionPane
                    .showInputDialog("Inserire Nome e Cognome del nuovo studente:"),
            Integer.parseInt(JOptionPane
                    .showInputDialog("Inserire la Media del nuovo studente:")));

}

// These are two methods that are called pressing other two buttons. But it doesn't matter.

public static void cercaNome() {}

public static void cercaMedia() {}
}

1 个答案:

答案 0 :(得分:3)

您可以使用JTable,其中第一列将存储密钥,第二列将存储值。

 Map<String,Integer> map=new HashMap<>();
 map.put("A",1);
 map.put("B",2);
 map.put("C",3);

 JTable table=new JTable(map.size(),2);
 int row=0;
 for(Map.Entry<String,Integer> entry: map.entrySet()){
      table.setValueAt(entry.getKey(),row,0);
      table.setValueAt(entry.getValue(),row,1);
      row++;
 }