将数组的内容添加到组合框中 [英] Add the contents of an array to a combo box

查看:641
本文介绍了将数组的内容添加到组合框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组(在另一个类中),其中包含10个值。
我想将此数组的值添加到组合框中。
这可能吗?
谢谢

I have an array (in another class) with 10 values in. I want to add the values of this array into a combo box. Is this possible? Thanks

推荐答案

当然:

Object[] yourArray = otherClass.getMyArray();
JComboBox box = new JComboBox (yourArray);

这将调用 Object.toString()获取要在组合框中显示的值,因此如果您使用自定义类,请确保它覆盖 toString()方法。

This will call Object.toString() to get the value to display in the combo box, so if you are using a custom class make sure it overrides the toString() method.

编辑:

在Netbeans中有几种​​方法可以做到这一点。这是一种方式。在表单的某处,有这样的方法:

There are a few ways to do this in Netbeans. Here's one way. Somewhere in your form, have a method like this:

private ComboBoxModel getComboModel (OtherClass myOtherClass)
{
  return new DefaultComboBoxModel (myOtherClass.getMyArray());
}

然后在表单设计器中:


  1. 点击组合框

  2. 在属性编辑器中编辑Model属性

  3. 选择现有组件的价值
  4. 下拉列表
  5. 选择方法调用单选按钮,然后选择 getComboModel()

  1. click on the combo box
  2. edit the Model propert in the properties editor
  3. select Value from existing component in the drop down
  4. select the Method call radio button and choose getComboModel()

还有很多其他方法可以做到这一点,但这适用于像你这样的简单案例。一般来说,如果你想使Netbeans友好,那么你需要提供一个返回ComboBoxModel实例的方法并指向它的Netbeans。

There are many other ways to do it, but this will work for a simple case like yours. In general, if you want to make it Netbeans friendly, then you need to provide a method somewhere that returns an instance of ComboBoxModel and point Netbeans at it.

这篇关于将数组的内容添加到组合框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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