Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 访问运行时创建的组件,并添加actionListener_Java_Swing_Awt - Fatal编程技术网

Java 访问运行时创建的组件,并添加actionListener

Java 访问运行时创建的组件,并添加actionListener,java,swing,awt,Java,Swing,Awt,在我的代码中,我在运行时创建组件,比如JTextField和JButton,我想将actionListener添加到程序执行期间创建的JButton中。 使用下面的代码,我只得到静态组件,而不是在运行时创建的新组件 static public <T extends Component> T getComponentByName(Window window, String name) { // loop through all of the class fields on t

在我的代码中,我在运行时创建组件,比如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 &lt;T&gt;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;
}

您可以使用window.getComponents()对组件进行迭代。

请说明原因……。您试图通过反射和代码实现什么?我实际上是从数据库中获取数据并按行显示,我想添加按钮,以获取该记录并执行一些操作,如在与该记录链接的其他表中添加记录。我想执行的其他任务很少,如创建不同的表单。额外的记录最好由
JTable
处理。通过
卡片布局创建新表单。。
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);