现在有个界面,上面有个文本框,属性名为"tf"
public class test2 extends JFrame {
//饿汉式单例,这个不重要
public static test2 instance = new test2();
//现在有一个JTextField
public JTextField tf = new JTextField("修改前\t该文本框字段名为'tf'");
private test2() {
//简单设置一下
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(null);
setLocationRelativeTo(null);
setTitle("测试界面2");
tf.setBounds(15,65,398,95);
tf.setFont(new Font("宋体", Font.PLAIN, 22));
getContentPane().add(tf);
}
public static void main(String[] args) {
instance.setVisible(true);
}
}
//测试修改文本框里的文字
public class test{
public static void main(String[] args) {
// 目的:通过取得文本框的名字来对该文本框进行setText操作
//测试界面的实例
test2 f = test2.instance;
//现已经知道该文本框属性名--放在一个String中
//限制:该属性名是存在字符串中的,所以直接通过对象调用不行
String str = "tf";
//我的尝试:想通过反射,发现不行
try {
//通过反射取得这个文本框属性
Field field = f.getClass().getField(str);
//发现直接set不行,我要修改的是文本框里的文字
field.set(f,"修改/增加后插入的值");
} catch (Exception e) {
e.printStackTrace();
}
f.setVisible(true);
}
}
有其他办法吗