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

Advertisement
サンプルコード
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(chooser)
.filter(JTable.class::isInstance).map(JTable.class::cast)
.findFirst()
.ifPresent(t -> t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN));
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JFileChooser
の詳細表示で使用されているJTable
を取得し、その自動サイズ変更モードを変更しています。
JPopupMenu
がJComponent#setComponentPopupMenu(...)
で設定されていてもその子Component
は取得しないJDK1.8
で導入された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; }
- 以下のように
参考リンク
- JFileChooserのデフォルトをDetails Viewに設定
- JFileChooserでの隠しファイルの非表示設定を変更する
- Get All Components in a container : Container « Swing JFC « Java