【发布时间】:2017-12-12 06:59:50
【问题描述】:
我有一个索引范围为 0-20 的组合 Bx(下拉框)。如果无论如何我可以使用该索引来指定我想要来自哪个对象的数据?所有对象都使用相同的命名约定 obj0、obj1、obj2 等。基本上是这样的......
public abstract class Person {
private String name;
private String title;
private String email;
private String job;
public Person(String name, String title, String email, String job){
this.name = name;
this.title = title;
this.email = email;
this.job = job;
}
//Getters and Setters
}
public class main extends javax.swing.JFrame {
...misc code...
private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {
Person obj0 = new Person("Jon Doe",
"Program Coordinator",
"jon.doe@test.com",
"Faculty");
Person obj1 = ...
...
Person obj20 = ...
/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {
//Uses the obj naming convention plus the index
string foo = "obj" + toString(combobox_Name.getSelectedIndex());
//Fills the textbox using the above string and the getName method
txtbox_username.setText(ToObject(foo).getName);
}
【问题讨论】:
-
我对你在问什么感到有点困惑。你有更多的代码给我们看吗?不确定组合框是什么,也不确定您所引用的这些对象是什么。
-
为什么需要这样做?
-
Java 无法识别对象具有名称的任何意义。您的意思是
obj0、obj1等是包含对感兴趣对象的引用的变量 的名称吗?在这种情况下,不,您不能在运行时使用字符串按名称访问变量。但是,您可以将感兴趣的对象放入Map,并将字符串作为相应的键。或者将它们放在List或数组中,并通过数字索引直接访问它们。 -
将元素放入一个列表中,然后为该列表建立索引。你真的不应该只是以数字结束变量,然后尝试像这样动态引用变量。
-
stackoverflow.com/questions/19094845/… 也许这会对你有所帮助?然后将项目存储在数组列表中?并根据需要添加类/变量/toString?