java通过变量名称引用组件

时间:2021-11-24 16:49:13

okay, i'm trying to figure out if there's a way to do the following:

好吧,我想弄清楚是否有办法做到以下几点:

say i have:

说我有:

jcombobox someCombo1 = new jcombobox();
jcombobox someCombo2 = new jcombobox();

changeSomething(someCombo1);
changeSomething(someCombo2);

i want to be able to refer to this combobox later, but by a variable from a method, say:

我想稍后能够引用这个组合框,但是通过方法中的变量,可以说:

public void changeSomething(jcombobox inCombo){
      inCombo.addItem("something")
}

so, that when the "something" item is added, it's added to the someCombo1, someCombo2 comboboxes, is this in any way possible?

那么,当添加“something”项时,它被添加到someCombo1,someCombo2组合框,这有可能吗?

am i looking at it wrong? haha

我看错了吗?哈哈

i have some code that manipulates A LOT of comboboxes with a long method body, each time, i want to condense it

我有一些代码用一个很长的方法体来操纵很多组合框,每一次,我想要浓缩它

1 个解决方案

#1


1  

I think you're looking for something like,

我觉得你在寻找类似的东西,

public static void changeSomething(JComboBox<String> inCombo){
      inCombo.addItem("something");
}

Note that it is JComboBox. Since your method doesn't depend on any instance fields I would make it static and you should not use raw-types.

请注意,它是JComboBox。由于您的方法不依赖于任何实例字段,我会将其设置为静态,您不应使用原始类型。

#1


1  

I think you're looking for something like,

我觉得你在寻找类似的东西,

public static void changeSomething(JComboBox<String> inCombo){
      inCombo.addItem("something");
}

Note that it is JComboBox. Since your method doesn't depend on any instance fields I would make it static and you should not use raw-types.

请注意,它是JComboBox。由于您的方法不依赖于任何实例字段,我会将其设置为静态,您不应使用原始类型。