views:

38

answers:

3

Hi! I'm trying to retrieve the text value from a JTextField but first I need to cast a component object (java.awt.Component) to a JTextFiel...

mi code is like this

Component[] x = this.getComponents(); 
    for(int i = 0; i < x.length; i++)
    {
        if (x[i] instanceof JTextComponent)
        {
               //retrieve text...something like
               //(JTextField)x[i].getText();
        }
    }

I'm doing this because I know all the controls of mi page are in "x" (JLabels and JTextField) but they are Components and that's why i'm making the cast to JTextField.

I'm really lost here and i don't know if this is the right way to do it. Thanks for your time!

+1  A: 

((JTextComponent) x[i]).getText(); should work.

(Just because x[i] is an instance of a JTextComponent, doesn't mean it's neccesarily a JTextField though.) But JTextComponent has a .getText() so casting to JTextComponent should be ok.

aioobe
+2  A: 

I think you need to rethink your design. Why not expose a getText() method in the class that contains your JTextField. That method can delete to your JTextField's getText() method, and avoid that God-awful instanceof.

Mike
+3  A: 

I'm really lost here and i don't know if this is the right way to do it. Thanks for your time!

You are never forced to write all you code on one line. So to simplify your problem simplify the code. Something like:

Component component = x[i];
JTextField textField = (JTextField)component;
String text = textField.getText();

That way if you have a compile error or something the compiler will point out the exact line.

camickr
+1 million points for my favorite suggestion to new programmers. Don't try and do everything on one line. Sometimes just writing out the steps of a tricky sequence helps me catch errors before a nasty compilation/debugging spiral.
RD
that's a great advice, thanks!
Hugo Assanti