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) b开发者_运维知识库ut 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!
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.
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
.
((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.
Through reflection API. Just for horizons expanding =)
import java.lang.reflect.Method;
...
for ( Component component : this.getComponents() ) {
try {
Method getText = component.getClass()
.getDeclaredMethod("getText");
String text = (String)getText.invoke();
//Do something with text
} catch ( Exception exc ) {} // no such method
}
精彩评论