在我的代码中,我在运行时创建组件,如JTextField和JButton,我想将actionListener添加到在程序执行期间创建的JButton中。 使用以下代码我只获取静态组件,但不是在运行时创建的新组件。
static public <T extends Component> T getComponentByName(Window window, String name) {
// loop through all of the class fields on that form
for (Field field : window.getClass().getDeclaredFields()) {
try {
// let us look at private fields, please
field.setAccessible(true);
// compare the variable name to the name passed in
if (name.equals(field.getName())) {
// get a potential match (assuming correct <T>ype)
final Object potentialMatch = field.get(window);
// cast and return the component
return (T) potentialMatch;
}
} catch (SecurityException ex) {
} catch(IllegalArgumentException ex) {
} catch(IllegalAccessException ex) {
// ignore exceptions
}
}
// no match found
return null;
}
在测试代码块中,我试图获得如下的组件
JLabel tt = new JLabel("testing");
this.jPanel_MainWrap.add(tt);
tt.setBounds(20,50,100,30);
JLabel txt = Awt1.getComponentByName(this, "jLabel1");
JOptionPane.showMessageDialog(null, "Error :" + txt.getText(), "InfoBox: ", JOptionPane.ERROR_MESSAGE);
答案 0 :(得分:0)
您可以使用window.getComponents()迭代组件。