【问题标题】:How to properly add JTextField components in the array?如何在数组中正确添加 JTextField 组件?
【发布时间】:2015-03-13 17:21:40
【问题描述】:

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

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

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

【问题讨论】:

  • 这似乎是一种非常标准的实现方式。什么会让你认为它错了?
  • .NET 人们会在这里使用 LINQ:P
  • @BinkanSalaryman Java 人可以使用流。我不知道你的评论有什么意义。
  • @Obicere,我认为有比这更简单的方法。
  • @Branislav Lazic 我不知道 :)

标签: java arrays swing jtextfield


【解决方案1】:

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

但是,如果您想变得花哨,可以使用 Darryl 的Swing Utils。基本代码是:

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

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

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2019-12-07
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多