简体   繁体   English

如果对象由多维数组保存,可以使用该方法吗?

[英]Can I use the method if the object is held by an multidimensional array?

I saw some post quite similar but did not hit spot on. 我看到了一些非常相似的帖子,但没有得到关注。

I was thinking something like this: 我在想这样的事情:

Object[][] test = {
          {"Name", new JTextField()},
          {"Gender", new JComboBox()}
}

I tried something like this but i cannot use the method of the JTextField or the JComboBox. 我尝试过类似的方法,但无法使用JTextField或JComboBox的方法。 How do I instantiate this depending on there 1-index? 如何根据那里的1索引实例化它? Is this possible? 这可能吗?

If you know for sure what it is, you can cast it when you get it out, like this 如果您确定它是什么,则可以在将其取出后进行投射,就像这样

JComboBox box = (JComboBox)(test[1][1]);
box.whatever();

However, instead of using an Object[][] , why not just make a class? 但是,为什么不使用Object[][]而不是仅仅创建一个类呢?

class UIWidgets {
    JTextField name;
    JComboBox gender;
}

You need to cast first before you can access methods specific to the type, since Java sees them all as instances of Object : 您需要先进行强制转换,然后才能访问特定于该类型的方法,因为Java将它们全部视为Object实例:

((JTextField)test[0][1]).CallMethodHere();

Or alternately: 或替代地:

JTextField tf = (JTextField)test[0][1];
// do something with tf

尝试这个:

((JTextField) test[0][1]).setText("someText");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM