更新 JComboBox [英] Updating JComboBox
问题描述
所以我将 JComboBox
与 ArrayList
一起使用:
So I'm using a JComboBox
with an ArrayList
:
protected JComboBox<String> jcb;
protected ArrayList<String> favourites;
favourites.add("Favourites");
favourites.add("-0.21 + 0.77");
favourites.add("-0.16 + -0.89");
jcb = new JComboBox(favourites.toArray());
这很好用,我可以选择每个选项并执行我需要执行的选定语句.但是,当我希望更新 JComboBox
时,它不会在我的 GUI 上更新.在我调用的另一种方法中:
This works fine and I can select each option and carry out the selected statements I need to do. However, when I wish to update the JComboBox
, it does not update on my GUI. In another method I call:
favourites.add("10 + 4");
jcb.revalidate();
jcb.repaint();
我已经测试过 ArrayList
已经更新(见下文),但是它没有显示在我的 GUI 上,有什么建议吗?谢谢,
I have Tested that the ArrayList
has been updated (see below), however It doesn't show on my GUI, any suggestions? Thanks,
for (String s : favourites)
System.out.println(s);
推荐答案
Swing 基于 MVC 模式.因此使用模型.对模型的更改将自动更新 JComboBox
.要更深入地了解一般情况,请阅读 Swing 架构概述 以及针对您的案例 如何使用组合框.
Swing is based on the MVC pattern. Thus use a model. Changes to the model will automatically update the JComboBox
. For a deeper understanding in general read Swing Architecture Overview and for your case How to use ComboBoxes.
DefaultComboBoxModel favourites = new DefaultComboBoxModel();
favourites.addElement("Favourites");
favourites.addElement("-0.21 + 0.77");
favourites.addElement("-0.16 + -0.89");
jcb = new JComboBox(favourites);
在另一个 GUI 方法调用中
in the other GUI method call
favourites.addElement("10 + 4");
这篇关于更新 JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!