Search code examples
javaswingjtextfield

Retrieve JTextField text value


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!


Solution

  • ((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.