首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >更新数组后更新JcomboBox

更新数组后更新JcomboBox
EN

Stack Overflow用户
提问于 2019-11-17 17:41:58
回答 1查看 139关注 0票数 1

我有一个JComboBox,它在我的主类中显示数组的内容,但我有另一个类,它有一个函数,它根据用户输入改变数组。然而,即使数组已经在主类中被更新,JComboBox也不会更新(我使用了一个打印来检查它是否确实更新)。在将更多项添加到数组或从数组中移除项时,JComboBox是否可以进行更新?

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

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-17 17:51:25

有几种解决办法,包括:

  • 使用观察者模式在数组更新时通知相关对象,然后为组合框创建一个新模型,并在发生更新时将其加载到组合框中。
  • 将创建您自己的模型类,扩展抽象组合框模型类,一个类使用数组本身,另一个类在数组更改时再次得到通知。
  • 完全摆脱了数组,而是在需要

时更新组合框模型。

任何解决方案的细节,包括代码,都将取决于当前程序的详细信息。

附带建议:

  • 您的组合框变量应该在initialize()方法中本地声明而不是,因为这将使类的其他成员看不到它,也不应该将任何其他对象分配给需要通过程序更改其状态的局部变量。将变量声明为类的私有实例字段。
  • 从不设置组件的界限或使用空布局,而是设置属性(可见行计数、原型显示值.)
  • 如果您的数组内容在程序ru期间可能会发生很大的变化,那么您可能应该使用一个集合,例如ArrayList<String>,或者更好的是使用自定义构建类的ArrayList<Building> .

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

代码语言:javascript
复制
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());
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58903312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档