문제

Is there a way to add two columns into a JComboBox in Netbeans?

I want to do the following: In a cboBox, I want to populate a list of countries with their ISO codes, eg.:

+----------------+---+
| Afghanistan    | V | < The Combo Box :D
+----------------+---+
         ↓↓↓
+----+---------------+
|ISO |  Country      |
+----+---------------+
| AF | Afghanistan   |
| AX | Åland Islands |
| AL | Albania       |
|... | ...           |
+----+---------------+

Then, When a user has selected a country, I need to extract the ISO code (col. 0) to store in a config file. This should later then be read again and be displayed as a country name, instead of the ISO code.

I've searched for a solution, but all I could find was how to put a cboBox into a JTable.

(This is the list I use/adapted: http://www.textfixer.com/resources/dropdowns/country-list-iso-codes.txt)

Thanks!

도움이 되었습니까?

해결책

What you should be doing is storing the data in Country objects, with fields name and iso. I really don't see the point of showing the iso in the combo box. From your drawing, you don't seem to want it show in the initial display, so why in the drop down?

For the display, you can use a DefaultListCellRenderer and extract the name value from each Country. When you select a country from the combo box, it will already be holding a List of Country objects, so you can extract the iso from the Country that is selected.

See example here. Note: the example only shows the country name, but if you really want the iso also, just change the rendering to setText(country.getIso() + " | " + country.getName());

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;

public class ComboBoxDemo {

    private List<Country> countries;
    private JComboBox cBox;

    public ComboBoxDemo() {
        countries = createCountryList();
        cBox = createComboBox(countries);

        JFrame frame = new JFrame();
        frame.add(cBox);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JComboBox createComboBox(List<Country> countries) {
        final JComboBox comboBox = new JComboBox(countries.toArray());
        comboBox.setRenderer(new ComboBoxRenderer());
        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Country country = (Country) comboBox.getSelectedItem();
                    System.out.println(country.getIso());
                }
            }
        });
        return comboBox;
    }

    private class ComboBoxRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list,
                    value, index, isSelected, cellHasFocus);
            Country country = (Country) value;
            label.setText(country.getName());
            return label;
        }
    }

    private List<Country> createCountryList() {
        List<Country> list = new ArrayList<>();
        list.add(new Country("Afghanistan", "AF"));
        list.add(new Country("Åland Islands", "AX"));
        list.add(new Country("Albania", "AL"));
        return list;
    }

    public class Country {
        private String name;
        private String iso;

        public Country(String name, String iso) {
            this.name = name;
            this.iso = iso;
        }

        public String getName() {
            return name;
        }

        public String getIso() {
            return iso;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxDemo();
            }
        });

    }
}

다른 팁

Using a custom renderer is only half of the answer. You also need to use a custom KeySelectionManager so you don't break the default selection functionality of the combo box when using the keyboard.

See Combo Box With Custom Renderer for a simple solution that combines the renderer and KeySelectionManager into one class. Or, you can check out the Combo Box With Hidden Data link in the blog for more information about the suggestion made by Timmos in Peeskillet's answer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top