JComboBox的更新 [英] Updating JComboBox

查看:329
本文介绍了JComboBox的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用的是的JComboBox 的ArrayList

  JComboBox的保护下&;串GT; JCB;
保护的ArrayList<串GT;收藏夹;
favourites.add(最爱);
favourites.add( - 0.21 + 0.77);
favourites.add( - 0.16 + -0.89);
JCB =新的JComboBox(favourites.toArray());

这工作正常,我可以选择每个选项并执行所选的语句,我需要做的。然而,当我要更新的的JComboBox ,它不会对我的GUI更新。在另一种方法我称之为:

  favourites.add(10 + 4);
jcb.revalidate();
jcb.repaint();

我已经测试了的ArrayList 已更新(见下文),但它不显示在我的GUI,有什么建​​议?谢谢,

 的(一个String:收藏)
的System.out.println(多个);


解决方案

Swing是基于MVC模式。因此,使用一个模型。更改模型会自动更新的JComboBox 。对于一般的读摇摆架构概述和你的情况的如何使用组合框

  DefaultComboBoxModel收藏夹=新DefaultComboBoxModel();
favourites.addElement(最爱);
favourites.addElement( - 0.21 + 0.77);
favourites.addElement( - 0.16 + -0.89);
JCB =新的JComboBox(收藏夹);

在其他GUI方法调用

  favourites.addElement(10 + 4);

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());

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();

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 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);

in the other GUI method call

favourites.addElement("10 + 4");

这篇关于JComboBox的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆