将项目动态添加到 JComboBox

Posted

技术标签:

【中文标题】将项目动态添加到 JComboBox【英文标题】:Dynamically adding items to a JComboBox 【发布时间】:2011-11-15 06:47:13 【问题描述】:
Vector comboBoxItems = new Vector();
DefaultComboBoxModel model;
// ComboBox Items have gotten from Data Base initially.
model = new DefaultComboBoxModel(ComboBoxItems);
JComboBox box = new JComboBox(model);

我将此组合框添加到面板中。如果我直接在数据库中添加一些项目,我希望那些新添加的项目显示在组合框中。

我在调试时可以看到comboBoxItems 中的值,但这些值没有出现在我的组合框中。

如何在不关闭面板的情况下将这些新添加的值放入组合框中?

【问题讨论】:

问题,可以使用 JComboBox 并且同时添加新项目 应该工作 - here's a snippet that uses the same constructor 您必须将项目添加到模型中,而不是添加到基础向量中 - 只有这样才能触发所需的通知! 【参考方案1】:

使用 ComboBoxModel 怎么样?像这样的......

    JFrame frame = new JFrame("Combo Box Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setLayout(new FlowLayout());

    Vector comboBoxItems=new Vector();
    comboBoxItems.add("A");
    comboBoxItems.add("B");
    comboBoxItems.add("C");
    comboBoxItems.add("D");
    comboBoxItems.add("E");
    final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
    JComboBox comboBox = new JComboBox(model);
    frame.add(comboBox);

    JButton button = new JButton("Add new element in combo box");
    frame.add(button);
    button.addActionListener(new ActionListener() 
        @Override
        public void actionPerformed(ActionEvent ae) 
            model.addElement("F");
        
    );

    frame.setVisible(true);

【讨论】:

【参考方案2】:

例如:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxSorted extends JFrame 

    private static final long serialVersionUID = 1L;
    private JComboBox comboBox;
    private JTextField textField;

    public ComboBoxSorted() 
        textField = new JTextField(15);
        textField.addActionListener(new ActionListener() 

            @Override
            public void actionPerformed(ActionEvent e) 
                comboBox.addItem(textField.getText());
                textField.setText("");
                comboBox.showPopup();
            
        );

        String[] items = "one", "two", "three", "four", "five";
        SortedComboBoxModel model = new SortedComboBoxModel(items);
        comboBox = new JComboBox(model);
        comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        JFrame frame = new JFrame("Add Item on Runtime");
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.add(comboBox, BorderLayout.SOUTH);
        frame.add(textField, BorderLayout.WEST);
        frame.add(new JLabel("Enter to add Item  "), BorderLayout.EAST);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    

    private class SortedComboBoxModel extends DefaultComboBoxModel 

        private static final long serialVersionUID = 1L;

        public SortedComboBoxModel() 
            super();
        

        public SortedComboBoxModel(Object[] items) 
            Arrays.sort(items);
            int size = items.length;
            for (int i = 0; i < size; i++) 
                super.addElement(items[i]);
            
            setSelectedItem(items[0]);
        

        public SortedComboBoxModel(Vector items) 
            Collections.sort(items);
            int size = items.size();
            for (int i = 0; i < size; i++) 
                super.addElement(items.elementAt(i));
            
            setSelectedItem(items.elementAt(0));
        

        @Override
        public void addElement(Object element) 
            insertElementAt(element, 0);
        

        @Override
        public void insertElementAt(Object element, int index) 
            int size = getSize();
            //  Determine where to insert element to keep model in sorted order            
            for (index = 0; index < size; index++) 
                Comparable c = (Comparable) getElementAt(index);
                if (c.compareTo(element) > 0) 
                    break;
                
            
            super.insertElementAt(element, index);
        
    

    public static void main(String[] args) 
        SwingUtilities.invokeLater(new Runnable() 

            @Override
            public void run() 
                ComboBoxSorted comboBoxSorted = new ComboBoxSorted();
            
        );
    

【讨论】:

【参考方案3】:

动态添加 JComboBox、JTextField 和 ImageIcon 等项目

Please,Show this image on display, how many items added or Table Fields size

After second images are display on Items like JComboBox,JTextField and ImageIcon

for example : count=3
//Dynamically Adding Items or Component above method
public void  dya_addcomp(int count)

//Dynamicly Drop/Delete icon
 BufferedImage Drop_Tablefield = null;
 try 
     Drop_Tablefield = ImageIO.read(this.getClass().getResource("/images/drop.png"));
  catch (IOException ex) 
     msg(" Error: drop and edit icon on Table, "+ex);
 
 //count Items for loop executed..
 for(int i=0;i<count;i++)
 
     //cnt++;
     //lblcount.setText("Count : "+cnt);
     JTextField txtcolnm=new JTextField("",20);
     JComboBox cmbtype=new JComboBox();
     JTextField txtcolsize=new JTextField("",20);

     JButton Drop_Table_Field = new JButton(new ImageIcon(Drop_Tablefield));

     cmbtype.addItem("INTEGER"); cmbtype.addItem("FLOAT");
     cmbtype.addItem("STRING");  cmbtype.addItem("BOOLEAN");

     colnamepanel.add(txtcolnm);   colnamepanel.add(cmbtype);
     colnamepanel.add(txtcolsize); colnamepanel.add(Drop_Table_Field);

     colnamepanel.setAutoscrolls(true);

     //refresh panel
     colnamepanel.revalidate();
     colnamepanel.repaint();

     //set the layout on Jpanel
     colnamepanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));

 

【讨论】:

【参考方案4】:

我从来没有找到一个整洁的方法来做到这一点,但你可以调用removeAllItems(),然后循环调用box.addItem(items[i]),它工作正常。

【讨论】:

以上是关于将项目动态添加到 JComboBox的主要内容,如果未能解决你的问题,请参考以下文章

将项目动态添加到列表小部件

将项目动态添加到 TableView 导致重复单元格

如何将JComboBox添加到JTable单元格?

将文件动态添加到 Visual Studio 部署项目

动态 UI 生成 - Java [关闭]

Eclipse - 将 .jar 添加到动态 Web 项目