Containerの子Componentを再帰的にすべて取得する
Total: 5374, Today: 3, Yesterday: 0
Posted by aterai at 
Last-modified: 
Summary
Containerの子Componentを再帰的にすべて取得するメソッドを作成し、JFileChooserに配置されたJTableを取得します。
Screenshot

Advertisement
Source Code Examples
public static Stream<Component> descendants(Container parent) {
  return Stream.of(parent.getComponents())
      .filter(Container.class::isInstance)
      .map(Container.class::cast)
      .flatMap(c -> Stream.concat(Stream.of(c), descendants(c)));
}
// ...
descendants(fileChooser)
  .filter(JTable.class::isInstance)
  .map(JTable.class::cast)
  .findFirst()
  .ifPresent(t -> t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN));
View in GitHub: Java, KotlinDescription
Stream#flatMap(...)を使用してすべての子コンポーネントを検索しそのストリームを取得する- 上記の関数で
JFileChooserのすべての子コンポーネントのストリームを取得し、さらにJFileChooserの詳細表示に使用されているJTableを絞り込む - 詳細表示用
JTableを発見したらその自動サイズ変更モードをJTable#setAutoResizeMode(...)で変更 JPopupMenuがJComponent#setComponentPopupMenu(...)で設定されていてもその子Componentは取得しない
- 上記の関数で
 
Stream#reduce(...)を使用して検索対象のルートコンテナを含めたすべてのコンポーネントを検索しそのストリームを取得する別方法:public static Stream<Component> descendantOrSelf(Container parent) { return Stream.of(parent.getComponents()) .filter(Container.class::isInstance) .map(c -> descendantOrSelf((Container) c)) .reduce(Stream.of(parent), Stream::concat); }
Streamは使用せずに再帰で検索する別方法:public static boolean searchAndResizeMode(Container parent) { for (Component c: parent.getComponents()) { if (c instanceof JTable) { ((JTable) c).setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); return true; } else if (c instanceof Container && searchAndResizeMode((Container) c)) { return true; } } return false; }
Reference
- JFileChooserのデフォルトをDetails Viewに設定
 - JFileChooserでの隠しファイルの非表示設定を変更する
 - Get All Components in a container : Container « Swing JFC « Java