Search code examples
javahashmapjbutton

How get the key of JButton in HashMap


i try get the key with the next code

    test = new HashMap<JButton, Character>();

    for (int fila=0, filaA = 0; fila<btn.length;fila++, filaA++){
        for (int columna=0, columnaA = 0;columna<btn[0].length;columna++, columnaA++){

            btn[fila][columna] = new JButton();
            test.put(btn[fila][columna], arr[filaA][columnaA]);
            btn[fila][columna].addMouseListener(new MouseListener(){
                public void mouseClicked(MouseEvent e) {

                    if(e.getSource() instanceof JButton){
                        String letra = ((JButton)e.getSource()).getText();
                        if(e.isMetaDown()){
                            if(letra.equals("T")){
                                ((JButton)e.getSource()).setText("O");
                            }
                            else if(letra.equals("O")){
                                ((JButton)e.getSource()).setText("");
                            }else{
                                ((JButton)e.getSource()).setText("T");
                            }
                        }else{
                            char k = test.get(((JButton)e.getSource()));
                            System.out.println(test.get(k));
                        }
                    }

                }
            });
            window.add(btn[fila][columna]); 
        }
    } 

but in:

else{
      char k = test.get(((JButton)e.getSource()));
      System.out.println(test.get(k));
}

when i try get the value assigned on each button only appears null. What I want is that every button, by giving click, show me your unique value on console.


Solution

  • System.out.println(test.get(k)); will return always null in your case, thats because the HashMap only has a builtin get(Object key) method and you trying to get a key object by a char value. There is no builtin method for retrieving the Key to a specific value such as eg: get(Object value) because all Values in a HashMap do not need to be unique unlike the keys.