Reputation: 1667
I have a panel that contains different components (JLabel, JButton, JTextComponent, etc). I want to get the list of JTextField in this way:
ArrayList<JTextField> arrayTf = new ArrayList();
Component[] arrayComponent = this.getComponents();
for (Component c : arrayComponent )
{
if (c instanceof JTextField ) {
arrayTf.add(c);
}
}
But I'm not sure that's the right way . Please tell me this is the right way ? Or is there an easier way? Thank U.
Upvotes: 0
Views: 69
Reputation: 324088
Your code is the simplest way.
However, if you want to get fancy then you can use Darryl's Swing Utils. The basic code would be:
List<JTextField> components = SwingUtils.getDescendantsOfType(JTextField.class, this, false);
The benefit of this class is that it is reusable. So you could easily get all the JButtons in one line without writing more code. Also, this code allows you to get components on the specified panel or the panel and all nested panels. There are a few other features as well.
Upvotes: 1