1

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. How do I instantiate this depending on there 1-index? Is this possible?

oneofakind
  • 564
  • 14
  • 40

3 Answers3

4

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?

class UIWidgets {
    JTextField name;
    JComboBox gender;
}
corsiKa
  • 76,904
  • 22
  • 148
  • 194
  • what if, we assuming that in the array it can be any objects anytime. So my casting cannot be static right? a class? What i'm really trying to do is to pass this Object[][], what ever the contents may be, and then create them. Like i said my casting cannot be constant considering the different possibilities. (try catch could be) but is there other ways to approach this? – oneofakind Aug 01 '12 at 06:30
2

You need to cast first before you can access methods specific to the type, since Java sees them all as instances of Object:

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

Or alternately:

JTextField tf = (JTextField)test[0][1];
// do something with tf
mellamokb
  • 53,762
  • 11
  • 101
  • 131
  • what if, we assuming that in the array it can be any objects anytime. So my casting cannot be static right? what other way to i approach this? – oneofakind Aug 01 '12 at 06:28
0

Try this:

((JTextField) test[0][1]).setText("someText");
Conner
  • 27,462
  • 8
  • 47
  • 72
higuaro
  • 14,758
  • 3
  • 32
  • 40