Java JComboBox是否可以将editable true设置为仅一个项目?

时间:2013-10-02 13:56:46

标签: java swing jcombobox

我想创建一个JComboBox,其上有三个项目。我想将可编辑设置为JComboBox的最后一项,例如:

JComboBox cb = new JComboBox();

cb.addItem("Dog");
cb.addItem("Cat");
cb.addItem("Other");

当我下拉JComboBox并选择项目其他.. JComboBox变得可编辑..我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以使用ItemListener了解所选的项目,然后根据需要设置JComboBox可编辑项。试试这个例子:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Demo {

      private void initGUI(){        
        Object[] items = new Object[]{"Dog","Cat","Other"};
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel(items);        

        final JComboBox comboBox = new JComboBox(dcbm);
        comboBox.setPreferredSize(new Dimension(200, 20));        
        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                Object selectedItem = comboBox.getSelectedItem();
                boolean editable = selectedItem instanceof String && ((String)selectedItem).equals("Other");
                comboBox.setEditable(editable);
            }
        });

        /*
         * Here you can add a new item to your JComboBox when it becomes editable
         */
        comboBox.getEditor().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object newItem = comboBox.getEditor().getItem();                  
                DefaultComboBoxModel dcbm = (DefaultComboBoxModel) comboBox.getModel();
                dcbm.addElement(newItem);
                dcbm.setSelectedItem(newItem);
            }
        });

        JPanel content = new JPanel(new FlowLayout());
        content.add(new JLabel("Test:"));
        content.add(comboBox);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().initGUI();
            }
        });      
    }
}

如您所见,当选择“其他”项时,JComboBox变为可编辑状态:

enter image description here

答案 1 :(得分:0)

这是一个演示(不是我),它似乎实现了你所追求的目标。 http://raginggoblin.wordpress.com/2010/05/04/jcombobox-with-disabled-items/