java 在swing中使用getComponent()调用一个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5281824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using getComponent() in swing to call a variable
提问by Puresilence
Alright this may seem like a weird question but is there a way that after calling something likejPanel3.getComponent(0).getName();
That I can use that value to make a call on a variable. Basically if it returns say jLabel1. That I can use that to call something on that label such as .setText("Hi"); Instead of having to type jLabel1.setText("hi"). Meaning can I use the returned value to directly call a function on it.
好吧,这似乎是一个奇怪的问题,但是有没有办法在调用jPanel3.getComponent(0).getName();
That 之类的东西后,我可以使用该值来调用变量。基本上,如果它返回说 jLabel1。我可以使用它来调用该标签上的某些内容,例如 .setText("Hi"); 而不必键入 jLabel1.setText("hi")。意思是我可以使用返回值直接调用它的函数。
采纳答案by Jon Bright
If I understood the question correctly, you want something like this:
如果我正确理解了这个问题,你想要这样的东西:
Component c=jPanel3.getComponent(0);
if (c instanceof JLabel)
((JLabel)c).setText("hi");
回答by Pa?lo Ebermann
The name
property of Components (i.e. getName()
and setName()
) have no relation to the variable which you once used when creating it. You can do this, for example (but don't, as this is very confusing):
name
Components的属性(即getName()
和setName()
)与您在创建它时曾经使用过的变量无关。例如,您可以这样做(但不要这样做,因为这非常令人困惑):
Component textField1 = new JLabel("text");
textField1.setName("comboBox1");
System.out.println(textField1.getName()); // comboBox1
There is no way to get back to your textField1
name - the variable may not even exist anymore when you are calling the getName()
method. You can even create (and use) components without ever using an explicit variable for them, like this:
没有办法回到你的textField1
名字 - 当你调用getName()
方法时,变量甚至可能不再存在。您甚至可以创建(和使用)组件,而无需为它们使用显式变量,如下所示:
panel.add(new JLabel("text"));
As written by Jon, you can cast the component to the real type, and don't need the name of the original variable.
正如 Jon 所写,您可以将组件强制转换为真实类型,而不需要原始变量的名称。