Java 获取 JPanel 组件

发布于 2024-07-09 15:56:47 字数 287 浏览 9 评论 0原文

我有一个充满 JTextFields 的 JPanel...

for (int i=0; i<maxPoints; i++) {
    JTextField textField = new JTextField();
    points.add(textField);
}

以后如何获取该 JPanel 中的 JTextFields? 就像我想要他们的价值观一样

TextField.getText();

谢谢

I have a JPanel full of JTextFields...

for (int i=0; i<maxPoints; i++) {
    JTextField textField = new JTextField();
    points.add(textField);
}

How do I later get the JTextFields in that JPanel? Like if I want their values with

TextField.getText();

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

小嗲 2024-07-16 15:56:47

Java 中的每个 JPanel 也是一个 AWT 容器。 因此,您应该能够使用 getComponents 获取面板中包含的组件的数组,迭代它们,检查它们的类型(以确保您没有获取其他控件),并对它们执行您需要的任何操作。

然而,这通常是糟糕的设计。 如果您知道需要访问特定组件,则最好维护这些文本字段的数组并将其传递,即使它们在视觉上包含在容器内。

如果这是一个经常性任务或者可以从多个点完成,那么甚至可以使用一个特殊的类来表示带有文本字段的面板,然后通过其界面提供访问这些字段的方法。

Every JPanel in Java is also an AWT container. Thus, you should be able to use getComponents to get the array of contained components in the panel, iterate over them, check their types (To make sure you didn't get other controls), and do whatever you need with them.

However, this is generally poor design. If you know that you will need to access specific components, it is better to maintain an array of those text fields and pass it around, even though they are visually contained within the container.

If this is a recurrent task or could be done from multiple points, it may even make sense to have a special class representing a panel with text fields, that will then provide through its interface means of accessing these fields.

小红帽 2024-07-16 15:56:47

请记住,他们自己并没有到达那里(我认为阅读一些有关在运行时动态创建这些面板的问题)

在那里发布的答案中,有人说您应该在数组中保留对这些文本字段的引用。 这正是您所需要的:

List<JTextField> list = new ArrayLists<JTextField>();

// your code...
for (int i=0; i<maxPoints; i++) { 
    JTextField textField = new JTextField();
    points.add(textField);
    list.add( textField ); // keep a reference to those fields.
}

// 后来

for( JTextField f : list ) { 
   System.out.println( f.getText() ) ;
}

不是那么容易吗?

请记住将这些类型的工件(列表)尽可能保密。 它们仅供您控制,我认为它们不属于界面。

假设您想要获取文本数组,而不是

 public List<JTextField> getFields();

您应该考虑:

 public List<String> getTexts(); // get them from the textfields ... 

Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime )

In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here:

List<JTextField> list = new ArrayLists<JTextField>();

// your code...
for (int i=0; i<maxPoints; i++) { 
    JTextField textField = new JTextField();
    points.add(textField);
    list.add( textField ); // keep a reference to those fields.
}

// Later

for( JTextField f : list ) { 
   System.out.println( f.getText() ) ;
}

Wasn't that easy?

Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface.

Let's say you want to get the array of texts, instead of

 public List<JTextField> getFields();

You should consider:

 public List<String> getTexts(); // get them from the textfields ... 
幻想少年梦 2024-07-16 15:56:47

您应该调用 getComponents 方法,该方法返回 JPanel 上所有元素的数组。 之后,您可以迭代数组并检查它是否与所寻找的组件相等。

List<JTextField> list = new ArrayLists<JTextField>();
Component[] components = panel.getComponents();

for (Component component : components) {
    if (component.getClass().equals(JTextField.class)) {
        list.add((JTextField)component);
    }
}

You should call the getComponents method this returns with an array of all elements on your JPanel. After you can iterate on the array and check if its equals with the sought after component.

List<JTextField> list = new ArrayLists<JTextField>();
Component[] components = panel.getComponents();

for (Component component : components) {
    if (component.getClass().equals(JTextField.class)) {
        list.add((JTextField)component);
    }
}
萤火眠眠 2024-07-16 15:56:47

这就是我递归地遍历容器并获取 JPanel 上的文本字段所做的事情。

private void ClearAllFields(Container myContainer) {

    Component myComps[] = myContainer.getComponents();

    for (int i=0; i<myComps.length; i++) {
      if(myComps[i] instanceof JPanel) {
          JPanel myPanel = (JPanel) myComps[i];
          ClearAllFields(myPanel);
      }
      if(myComps[i] instanceof JTextField) {
        JTextField myTextField = (JTextField) myComps[i];
        myTextField.setText("");
      }
    }        
}

然后使用它,你可以这样称呼它

ClearAllFields([jdialog or jframe etc].getContentPane());

This is what I did to recursively go through the container and get the textfields that are on the JPanels.

private void ClearAllFields(Container myContainer) {

    Component myComps[] = myContainer.getComponents();

    for (int i=0; i<myComps.length; i++) {
      if(myComps[i] instanceof JPanel) {
          JPanel myPanel = (JPanel) myComps[i];
          ClearAllFields(myPanel);
      }
      if(myComps[i] instanceof JTextField) {
        JTextField myTextField = (JTextField) myComps[i];
        myTextField.setText("");
      }
    }        
}

And then to use it, you call it this way

ClearAllFields([jdialog or jframe etc].getContentPane());
莫多说 2024-07-16 15:56:47
    //una forma de recorer todos los elementos dentro de un jpanel
    Component[] components = jPanelX.getComponents();

    for (int i = 0; i < components.length; i++) {

        if(components[i].getClass().getName().toString().equals("javax.swing.JTextField")){
            components[i].setEnabled(false);
        }
    }
    //una forma de recorer todos los elementos dentro de un jpanel
    Component[] components = jPanelX.getComponents();

    for (int i = 0; i < components.length; i++) {

        if(components[i].getClass().getName().toString().equals("javax.swing.JTextField")){
            components[i].setEnabled(false);
        }
    }
吃素的狼 2024-07-16 15:56:47

在创建过程中动态为其命名,然后执行此操作。

    Component[] components = panel.getComponents();
    for (Component component: components) {
        var name = component.getName();  
        if(name != null){    
            if(name.equals("textfield 1")){
                var field = (JTextField)component;
                field.setText("whatever you want / same for options and other components")
            }
        }

    }

Dynamicly give it a name during creation and then do this.

    Component[] components = panel.getComponents();
    for (Component component: components) {
        var name = component.getName();  
        if(name != null){    
            if(name.equals("textfield 1")){
                var field = (JTextField)component;
                field.setText("whatever you want / same for options and other components")
            }
        }

    }
温馨耳语 2024-07-16 15:56:47

您的问题是编写乏味的代码文本。 为什么不直接生成它并粘贴到程序中!!...

for(int i=1 ; i<=maxpoints ;i++){
   System.out.println("JTextField tf"+i+" = new JTextField()"+";");
   System.out.println("points.add(tf"+i+")"+";");
}

将上述代码的输出粘贴到您的程序中,您就完成了。
现在,要访问文本字段的内容,您可以以类似的方式生成繁琐的代码文本......

for(int i=1 ; i<=maxpoints ;i++){
   System.out.println("String s"+i+" = JTextField tf"+i+".getText()"+";");
}

Your problem is writing the tedious code text. Why not just generate it and paste in the program!!...

for(int i=1 ; i<=maxpoints ;i++){
   System.out.println("JTextField tf"+i+" = new JTextField()"+";");
   System.out.println("points.add(tf"+i+")"+";");
}

Paste the output of the above code in your program and you are done.
Now, to access the content of text fields you can generate the tedious code text in a similar way....

for(int i=1 ; i<=maxpoints ;i++){
   System.out.println("String s"+i+" = JTextField tf"+i+".getText()"+";");
}
徒留西风 2024-07-16 15:56:47
public Component getComponentByName(Container parent,String name) {
        java.util.List<Component> clist = new ArrayList<>();
        listAllComponentsIn(parent,clist);
        for (Component c : clist) {
            System.out.println(c.getName());
            String s = c.getName();
            if(s!=null){
                if(s.equals(name)){
                    return c;
                }
            }
        }
        return null;
    }
    public void listAllComponentsIn(Container parent,java.util.List<Component> components)
    {
        for (Component c : parent.getComponents()) {
            components.add(c);
            if (c instanceof Container) {
                listAllComponentsIn((Container) c,components);
            }
        }
    }

如果您有父母,那么您可以随时随地获取您的文本字段。
例如,我已在名为 searchBar 的 JPanel 上添加了文本字段。
首先我给textField起了一个名字(“txt_search_box”),然后我能够
从任何地方获取此文本字段,因为我通过以下方式引用了 JPanel(searchBar)
使用这个-

searchBar.setVisible(true);
                        JTextField jTextField = (JTextField) getComponentByName(searchBar,"txt_search_box");
                        if(jTextField!=null){
                            jTextField.requestFocusInWindow();
                        } 
public Component getComponentByName(Container parent,String name) {
        java.util.List<Component> clist = new ArrayList<>();
        listAllComponentsIn(parent,clist);
        for (Component c : clist) {
            System.out.println(c.getName());
            String s = c.getName();
            if(s!=null){
                if(s.equals(name)){
                    return c;
                }
            }
        }
        return null;
    }
    public void listAllComponentsIn(Container parent,java.util.List<Component> components)
    {
        for (Component c : parent.getComponents()) {
            components.add(c);
            if (c instanceof Container) {
                listAllComponentsIn((Container) c,components);
            }
        }
    }

if you have parent then you can get your textField anytime, anywhere.
for example, i have added my textField on a JPanel named searchBar.
first i gave a name ("txt_search_box") to textField and then i was able to
get this textField from anywhere because i had reference to JPanel(searchBar) by
using this-

searchBar.setVisible(true);
                        JTextField jTextField = (JTextField) getComponentByName(searchBar,"txt_search_box");
                        if(jTextField!=null){
                            jTextField.requestFocusInWindow();
                        } 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文