Jcombobox does not allow item change

Asked

Viewed 736 times

5

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

In the jPanel There are two other combos that are identical with the one that has the behavior explained, but they work perfectly, in case I wanted to change item is allowed. I already created a test but the behavior persists.

Can anyone tell me what it might 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);
  • You have properly implemented the method equals() in class Bem?

  • That’s right, it wasn’t implemented correctly. Thank you very much!

  • Cool, I’ll add as an answer to make the question correct.

1 answer

3


This type of problem is usually caused by an incorrect implementation of the method equals() of the class representing 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 searching for the element in the list, the first element will always be the result of the comparison.

The example below corrects 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);

    }

}
  • 1

    Are you sure you haven’t made any mistakes? You’re comparing Strings using ==. In addition, your method equals gives ClassCastException if the type of the parameter is not a Bem or NullPointerException if it’s null. Is also missing the hashCode().

  • @Victor Thanks. I must have pasted the wrong code in the reply. Tomorrow I will review it.

  • 1

    @Victor had actually pasted two incorrect examples, I must have got confused when editing the answer. Again. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.