0

First of all sorry for my english. I'm trying to build a program that gets inputs from the user by JOptionPane.showInputDialog() and store it in an HashMap<String, Integer>.

I did it and it works.

But the problem is that i want to print all the HashMap keys and values in a swing component (JList or JTable or something else) but i don't know wich is better and simple to use. Wich do you suggest?


Masud thanks for your reply but i tryied your code and it gives me an error:

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)

In the error: line 91 is where i wrote table.setValueAt(entry.getKey(), row, 0); inside the for loop. And line 43 is where i call the method where the for loop is.

I tryed to fix it but i've solved nothing. I just saw that this error appears just when i print the HashMap with the input given from JOptionPane.showInputDialog(). If i set the HashMap key and values inside the code it works perfectly. Any idea to solve it?

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

This is the code:

import java.awt.Container;

public class Main extends 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() {}
}
Marcello Davi
  • 433
  • 4
  • 16
  • depends of structure, there are a few ways, for more info to read Oracle Swing tutorials – mKorbel May 25 '14 at 13:43
  • Read it here [How can I create a JList that contains entries of a Hashtable of String and Object?](http://stackoverflow.com/questions/8747458/how-can-i-create-a-jlist-that-contains-entries-of-a-hashtable-of-string-and-obje). It might help you. – Braj May 25 '14 at 13:43

1 Answers1

3

You can use JTable where first column will store key and second column will store value.

 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++;
 }
Masudul
  • 21,823
  • 5
  • 43
  • 58