开发者

JComboBox Item Change

My JComboBox model contains item like item1, item2, item1. My problem is when I select third item (item1) in JComboBox and check getSel开发者_Python百科ectedIndex() it always returns 0.

If the item is same in my model how can I get index of each item differently? Like:

  • item1 returns 0
  • item 2 returns 1
  • item1 returns 2


It returns index = 0. Because the method getSelectedIndex() use .equals on objects that are in the JComboBox and compare it with the selected one. In your case because item1 is also at index 0 it finds the condition true and returns 0. If you want to get different index then you have to override the getSelectedIndex() method.

An outline of default getSelectedIndex() method of JComboBox found at Java2s:

public int getSelectedIndex() {
        Object sObject = dataModel.getSelectedItem();
        int i, c;
        Object obj;

        for (i = 0, c = dataModel.getSize(); i < c; i++) {
            obj = dataModel.getElementAt(i);
            if (obj != null && obj.equals(sObject))
                return i;
        }
        return -1;
    }

You should have something [may be itemName if item object has a name or anything else] different in 2 entries to get desired result. Override getSelectedIndex() and compare the thing that is meant to be differ in all. If both entries are completely same then whats the point of adding it twice?


If two entries in the JComboBox correspond to the same Object, then even if you click item 3 the actual item that is selected will be the first entry of that object (i.e. the one with the lowest index) I don't think that this will work for the same objects.


A JList has no problems with identical items.

JComboBox Item Change

import javax.swing.event.*;
import javax.swing.*;

class TestList {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final String[] items = {"item1", "item2", "item1"};
                final JList list = new JList(items);
                final JTextField output = new JTextField(15);
                JPanel gui = new JPanel();
                gui.add(list);
                gui.add(output);
                list.addListSelectionListener(new ListSelectionListener(){
                    public void valueChanged(ListSelectionEvent lse) {
                        int index = list.getSelectedIndex();
                        String outputText =
                            "Index: " +
                            index +
                            "  Value: " +
                            items[index];
                        output.setText(outputText);

                    }
                });
                JOptionPane.showMessageDialog(null, gui);
            }
        });
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜