如何在数组中正确添加 JTextField 组件?

How to properly add JTextField components in the array?

我有一个包含不同 组件(JLabel、JButton、JTextComponent 等)的面板。我想通过这种方式获取 JTextField 的列表:

ArrayList<JTextField> arrayTf = new ArrayList();
Component[] arrayComponent = this.getComponents();
for (Component c : arrayComponent )
{   
    if (c instanceof JTextField ) {
        arrayTf.add(c);
    }
}

但我不确定这是正确的方法。请告诉我这是正确的方法吗?或者有更简单的方法吗?谢谢你

你的代码是最简单的方法。

但是,如果你想要花哨一些,那么你可以使用 Darryl 的 Swing Utils。基本代码为:

List<JTextField> components = SwingUtils.getDescendantsOfType(JTextField.class, this, false);

这个 class 的好处是它可以重复使用。因此,您可以轻松地在一行中获取所有 JButton,而无需编写更多代码。此外,此代码允许您获取指定面板或面板和所有嵌套面板上的组件。还有一些其他功能。