Java Swing How to - Get a component recursively within a container








Question

We would like to know how to get a component recursively within a container.

Answer

import java.awt.Component;
import java.awt.Container;
import java.io.File;
// w  w w  . j  ava2  s .c om
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button = new JButton("Click me");
    button.addActionListener(e -> {
      JFileChooser chooser = new JFileChooser();
      chooser.setSelectedFile(new File(chooser.getCurrentDirectory(),
          "save.dat"));
      final JTextField textField = getTexField(chooser);
      if (textField == null) {
        return;
      }
      String text = textField.getText();
      if (text == null) {
        return;
      }
      int index = text.lastIndexOf('.');
      if (index == -1) {
        return;
      }
      textField.setSelectionStart(0);
      textField.setSelectionEnd(index);

      chooser.showSaveDialog(button);

    });
    frame.add(button);
    frame.pack();
    frame.setVisible(true);
  }

  private static JTextField getTexField(Container container) {
    for (int i = 0; i < container.getComponentCount(); i++) {
      Component child = container.getComponent(i);
      if (child instanceof JTextField) {
        return (JTextField) child;
      } else if (child instanceof Container) {
        JTextField field = getTexField((Container) child);
        if (field != null) {
          return field;
        }
      }
    }
    return null;
  }
}