从动态添加的 jPanel 获取文本 [英] get text from dynamically added jPanel

查看:35
本文介绍了从动态添加的 jPanel 获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 subPanel 动态添加到 jPanel1(使用 jTextFieldjButton).部分代码借鉴自 那里.

I am adding dynamically subPanel to jPanel1 (with jTextField and jButton). Some of part code was borrowed from there.

我正在尝试从 jPanel1 的组件中获取文本,但无法成功.

I am trying to get text from components of jPanel1, but cannot succeed.

这是一个包含 jTextField+Button-Button 的子面板.

EDITED: This is a subPanel that contains jTextField, +Button and -Button.

private class subPanel extends javax.swing.JPanel {         
        subPanel me;
        public subPanel() {
            super();
            me = this;
            JTextField myLabel = new JTextField(15);
            add(myLabel);
            JButton myButtonRemove = new JButton("-");
            JButton myButtonAdd = new JButton("+");
            add(myButtonRemove);
            add(myButtonAdd);

这是AddButton的代码:

Here is code of AddButton:

    jPanel1.add(new subPanel());
    pack();

我试图获取文本的代码来自 jTextField 不起作用:

The code that I am trying to get text from jTextField doesn't work:

     Component[] children = jPanel1.getComponents();
     for (int i=0;i<children.length;i++){
     if (children[i] instanceof JTextField){
     String text = ((JTextField)children[i]).getText();
     System.out.println(text);

}

您的回复将不胜感激.

推荐答案

问题是:您正在迭代 jPanel1 的孩子:

Problem is: You are iterating over the children of jPanel1:

jPanel1.getComponents();

并期望有一个 JTextField:

if (children[i] instanceof JTextField){
     String text = ((JTextField)children[i]).getText();
     System.out.println(text);
}

但是由于您已将 subPanels 添加到 jPanel1,jPanel1 的子项是 subPanels,而不是 JTextFields

But since you have added subPanels to jPanel1, the children of jPanel1 are subPanels, not JTextFields!

因此,为了访问 JTextFields,您必须在第二个 for-loop 中迭代 subPanels 的子项>!

So, in order to access the JTextFields, you'll have to iterate over the children of the subPanels in a second for-loop!

示例:

Component[] children = jPanel1.getComponents();
// iterate over all subPanels...
for (Component sp : children) {
    if (sp instanceof subPanel) {
        Component[] spChildren = ((subPanel)sp).getComponents();
        // now iterate over all JTextFields...
        for (Component spChild : spChildren) {
            if (spChild instanceof JTextField) {
                String text = ((JTextField)spChild).getText();
                System.out.println(text);
            }
        }
    }
}

这篇关于从动态添加的 jPanel 获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆