Retrieve JTextField text value

瘦欲@ 提交于 2019-12-23 04:24:29

问题


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:


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




回答2:


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.




回答3:


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.




回答4:


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
  }


来源:https://stackoverflow.com/questions/3885577/retrieve-jtextfield-text-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!