简体   繁体   English

Java 获取 JPanel 组件

[英]Java get JPanel Components

I have a JPanel full of JTextFields...我有一个充满 JTextFields 的 JPanel ......

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

How do I later get the JTextFields in that JPanel?我以后如何在该 JPanel 中获取 JTextFields? Like if I want their values with就像我想要他们的价值观一样

TextField.getText();

Thanks谢谢

Every JPanel in Java is also an AWT container. Java 中的每个 JPanel 也是一个 AWT 容器。 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.因此,您应该能够使用 getComponents 来获取面板中包含的组件数组,对其进行迭代,检查它们的类型(以确保您没有获得其他控件),并对它们进行任何您需要的操作。

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.如果这是一个经常性的任务或者可以从多个点完成,甚至可以有一个特殊的类来表示一个带有文本字段的面板,然后通过它的接口提供访问这些字段的方法。

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 ... 

This is what I did to recursively go through the container and get the textfields that are on the JPanels.这就是我递归遍历容器并获取 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("");
      }
    }        
}

And then to use it, you call it this way然后使用它,你这样称呼它

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

You should call the getComponents method this returns with an array of all elements on your JPanel.您应该调用 getComponents 方法,该方法返回 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);
    }
}
    //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);
        }
    }

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")
            }
        }

    }

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()"+";");
}
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.例如,我在名为 searchBar 的 JPanel 上添加了我的 textField。 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-首先,我给 textField 起了一个名字(“txt_search_box”),然后我可以从任何地方获取这个 textField,因为我通过使用这个引用了 JPanel(searchBar)-

searchBar.setVisible(true);
                        JTextField jTextField = (JTextField) getComponentByName(searchBar,"txt_search_box");
                        if(jTextField!=null){
                            jTextField.requestFocusInWindow();
                        } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM