加上在Java组合框项目运行(add items runtime on combobox in ja

2019-07-31 17:22发布

我创建了一个Swing 组合框 ,我想在其他功能上添加项目。 但问题是,项目不会调用该函数后会显示:

public void addItems()
{
    combo.addItem("");
    // i want to add items here when this function is being called
    // but those items are not displaying after calling this function
    // i m calling this function on button click
}

Answer 1:

在这个工作对我来说SSCCE :

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox {

    private int count = 0;

    protected void initUI() {
        final JFrame frame = new JFrame(TestComboBox.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JComboBox comboBox = new JComboBox(new Object[] { "Something", "Stuff", "Beep" });
        JButton add = new JButton("Add item");
        add.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                comboBox.addItem("Item-" + count++);
            }
        });
        frame.add(comboBox);
        frame.add(add, BorderLayout.SOUTH);
        frame.pack();
        frame.setBounds(50, 50, 300, frame.getHeight());
        frame.setVisible(true);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestComboBox().initUI();
            }
        });
    }
}


Answer 2:

如果你的组合框有MutableComboBoxModel ,你可以做以下

MutableComboBoxModel model = (MutableComboBoxModel)combo.getModel();
model.addElement( elementToAdd );

这等同于调用JComboBox#addItem (见下文实施):

public void addItem(Object anObject) {
    checkMutableComboBoxModel();
    ((MutableComboBoxModel)dataModel).addElement(anObject);
}

但我认为这是直接修改模型,如果你想在模型方面的变化,而不是去通过视图(除向用户提供在视图编辑能力)最佳实践



Answer 3:

你需要调用:

repaint();
validate();


文章来源: add items runtime on combobox in java