JComboBox does not allow item exchange

5

I have a JComboBox that allows to select only the first item clicked, in case I want to change the selection it does not allow.

No jPanel has two other combos that are identical with what has the behavior explained, but they work perfectly, if I wanted to change item is allowed. I've already created a test, but the behavior persists.

Can anyone tell me what it can be?

final JComboBox comboBoxBem = new JComboBox();
comboBoxBem.setToolTipText("Descri\u00E7\u00E3o do Bem");
comboBoxBem.setForeground(new Color(0, 0, 0));
comboBoxBem.setFont(new Font("Tahoma", Font.BOLD, 11));
comboBoxBem.setBounds(365, 314, 402, 20);
comboBoxBem.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
    if (comboBoxBem.getSelectedItem() != null) {
      try {
        InformacoesDoBemBean informacoesDoBem;
        if (comboBoxBem.getSelectedItem() != null &&
            comboBoxBem.getSelectedItem() instanceof Bem) {
          Bem bem = (Bem)comboBoxBem.getSelectedItem();
          informacoesDoBem = controller.getInformacoesDoBem(bem.getCodigo(),
                                                            bem.getPatrimonio());
          if (informacoesDoBem != null) {
            textFieldNumeroDoBem.setText(informacoesDoBem.getCodigo());
            textFieldResponsavelPelaArea.setText(informacoesDoBem.getNomeResponsavel());
            textFieldPatrimonio.setText(informacoesDoBem.getPatrimonio());
            textPanelDescricao.setText("");
            lblValorCaractRestante.setText("80");
          }
        }
      } catch(Exception ex) {
        logger.error("####ERRO AO OBTER INFORMAÇÕES DO BEM: ", ex);
        JOptionPane.showMessageDialog(container,
          "Ocorreu um erro ao carregar as informações do bem, tente novamente");
      }
    }
  }
});
AutoCompleteDecorator.decorate(comboBoxBem);
container.add(comboBoxBem);
    
asked by anonymous 09.01.2014 / 15:05

1 answer

3

This type of problem is usually caused by an incorrect implementation of the equals() method of the class that represents the JComboBox elements.

For example, the following class reproduces the problem:

public class Bem {

    private String nome;
    public Bem(String nome) {
        this.nome = nome;
    }

    @Override
    public boolean equals(Object obj) {
        return obj == nome; // implementação incorreta, nunca vai retornar verdadeiro
    }

    @Override
    public String toString() {
        return nome;
    }

    public static void main(String[] args) {

        //combo
        final JComboBox combo = new JComboBox();
        combo.addItem(new Bem("Teste1"));
        combo.addItem(new Bem("Teste2"));
        combo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (combo.getSelectedItem() != null) {
                    System.out.println("Selected: " + combo.getSelectedIndex() + " - " + combo.getSelectedItem());
                }
            }
        });

        //window
        JFrame f = new JFrame("Test Combo");
        f.getContentPane().add(combo);
        f.setSize(200,  200);
        f.setVisible(true);

    }

}

Note that the equals method is comparing something that will always return true, so when looking for the element in the list, the first element will always be the result of the comparison.

The following example fixes the problem:

public class Bem {

    private String nome;
    public Bem(String nome) {
        this.nome = nome;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Bem)) return false;
        return obj == this || nome.equals(((Bem) obj).nome);
    }

    @Override
    public String toString() {
        return nome;
    }

    public static void main(String[] args) {

        //combo
        final JComboBox combo = new JComboBox();
        combo.addItem(new Bem("Teste1"));
        combo.addItem(new Bem("Teste2"));
        combo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (combo.getSelectedItem() != null) {
                    System.out.println("Selected: " + combo.getSelectedIndex() + " - " + combo.getSelectedItem());
                }
            }
        });

        //window
        JFrame f = new JFrame("Test Combo");
        f.getContentPane().add(combo);
        f.setSize(200,  200);
        f.setVisible(true);

    }

}
    
09.01.2014 / 15:39