【问题标题】:update JcomboBox after Array is updatedArray 更新后更新 JcomboBox
【发布时间】:2019-11-17 17:41:58
【问题描述】:

我有一个 JComboBox,它在我的主类中显示一个数组的内容,但我有另一个类,它具有根据用户输入更改数组的函数。然而,即使数组已在主类中更新,JComboBox 也不会更新(我使用打印来检查它是否确实更新了)。有没有办法让 JComboBox 在向数组中添加更多项或从数组中删除项时更新?

这是主类中的JComboBox,其中buildingNames是存储信息的数组,将被更新。

private String[] buildingNames;

public mainWindow() {
    initialize();
}

private void initialize() {
    frame = new JFrame("Main Window");
    frame.setBounds(0, 0, 1280, 720);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.setBackground(Color.WHITE);
    frame.setResizable(false);

    buildingNames = {"Costlemark","Science","Research"} //This will get updated

    DefaultComboBoxModel BuildingModel = new DefaultComboBoxModel(buildingNames);
    JComboBox selectBuilding = new JComboBox(BuildingModel);
    selectBuilding.setBounds(46, 82, 150, 40);
    frame.getContentPane().add(selectBuilding);
}

【问题讨论】:

    标签: java swing jcombobox


    【解决方案1】:

    存在几种解决方案,包括:

    • 使用观察者模式在数组更新时通知相关对象,然后为组合框创建新模型,并在更新发生时将其加载到组合中。这将是更大的模型-视图-控制器程序结构的一部分,并且可能是我要走的路。
    • 创建您自己的模型类,扩展抽象组合框模型类,一个使用数组本身,另一个在数组更改时再次收到通知。
    • 完全摆脱数组,而是在需要的时间和地点更新组合框模型

    任何解决方案的详细信息(包括代码)都取决于您当前程序的详细信息。

    建议:

    • 您的组合框变量不应initialize() 方法中本地声明,因为这将使其对类的其余部分不可见,任何其他对象也不应分配给需要由程序更改其状态的局部变量。将变量声明为类的私有实例字段。
    • 切勿设置组件的边界或使用空布局,而是设置属性(可见行数、原型显示值...)并允许组件自行调整大小。
    • 如果您的数组内容可能会在程序 ru 期间发生相当大的变化,那么您可能应该使用自定义 Building 类的 ArrayList<String> 之类的集合,甚至更好的是 ArrayList<Building>。李>

    最后一个我们只使用组合框模型的建议示例:

    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class BuildingTest extends JPanel {
        // model to hold all the building name strings
        private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>(new String[] {"Foo", "Bar", "Baz"});
        private JComboBox<String> selectBuildingCombo = new JComboBox<>(comboModel);
    
        // text field to allow user to add more strings to model
        private JTextField entryField = new JTextField(10);
        private JButton enterBuildingBtn = new JButton("Enter Building Name");    
    
        public BuildingTest() {
            // the size of the combobox larger
            selectBuildingCombo.setPrototypeDisplayValue("abcdefghijklmnopqrstuv");
            add(selectBuildingCombo);
            add(new JLabel("Enter new building name:"));
            add(entryField);
            add(enterBuildingBtn);
    
            selectBuildingCombo.addActionListener(e -> {
                String selection = (String) selectBuildingCombo.getSelectedItem();
                if (selection != null) {
                    System.out.println("Selected Item: " + selection);
                }
            });
    
            // occurs when user wants to add to combo model
            ActionListener enterBuildingListener = e -> {
                // get text from text field
                String text = entryField.getText().trim();
                if (!text.isEmpty()) {
                    // if not empty, add to model
                    comboModel.addElement(text);
                    entryField.selectAll();
                }
            };
    
            // add this action listener to both the text field and the button
            enterBuildingBtn.addActionListener(enterBuildingListener);
            entryField.addActionListener(enterBuildingListener);
            enterBuildingBtn.setMnemonic(KeyEvent.VK_E);
        }
    
        private static void createAndShowGui() {
            BuildingTest mainPanel = new BuildingTest();
    
            JFrame frame = new JFrame("Building Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    【讨论】:

    • 非常感谢您的回答和建议!我已经尝试了你的建议,它奏效了! :) 再次感谢您!
    猜你喜欢
    • 2014-04-11
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多