Swing/GetComponentsRecursively のバックアップの現在との差分(No.1)
- category: swing folder: GetComponentsRecursively title: Containerの子Componentを再帰的にすべて取得する tags: [Container, Component, JFileChooser, JTable] author: aterai pubdate: 2017-02-06T14:11:50+09:00 description: Containerの子Componentを再帰的にすべて取得するメソッドを作成し、JFileChooserに配置されたJTableを取得します。 image: https://drive.google.com/uc?export=view&id=1NedWhPhVuMDTwrHRaFdW-YXZjdH-019yuw image: https://drive.google.com/uc?id=1NedWhPhVuMDTwrHRaFdW-YXZjdH-019yuw
概要
Container
の子Component
を再帰的にすべて取得するメソッドを作成し、JFileChooser
に配置されたJTable
を取得します。
Screenshot
Advertisement
Screenshot
Advertisement
サンプルコード
#spandel
public static Stream<Component> stream(Container parent) {
#spanend
return Arrays.stream(parent.getComponents())
.filter(Container.class::isInstance).map(c -> stream(Container.class.cast(c)))
.reduce(Stream.of(parent), Stream::concat);
#spanadd
public static Stream<Component> descendants(Container parent) {
#spanend
return Stream.of(parent.getComponents())
.filter(Container.class::isInstance)
.map(Container.class::cast)
.flatMap(c -> Stream.concat(Stream.of(c), descendants(c)));
}
#spandel
//...
#spanend
#spandel
stream(chooser)
#spanend
.filter(JTable.class::isInstance).map(JTable.class::cast)
#spanadd
// ...
#spanend
#spanadd
descendants(fileChooser)
#spanend
.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
を取得(JDK1.8
で導入されたStream
を使用)し、その自動サイズ変更モードを変更しています。
-
Stream#flatMap(...)
を使用してすべての子コンポーネントを検索しそのストリームを取得する- 上記の関数で
JFileChooser
のすべての子コンポーネントのストリームを取得し、さらにJFileChooser
の詳細表示に使用されているJTable
を絞り込む - 詳細表示用
JTable
を発見したらその自動サイズ変更モードをJTable#setAutoResizeMode(...)
で変更 -
JPopupMenu
がJComponent#setComponentPopupMenu(...)
で設定されていてもその子Component
は取得しない
- 上記の関数で
- -
以下のように、
Stream
を使用しない方法も多数あります。
-
Stream#reduce(...)
を使用して検索対象のルートコンテナを含めたすべてのコンポーネントを検索しそのストリームを取得する別方法:#spanend #spanadd public static Stream<Component> descendantOrSelf(Container parent) { #spanend return Stream.of(parent.getComponents()) .filter(Container.class::isInstance) .map(c -> descendantOrSelf((Container) c)) .reduce(Stream.of(parent), Stream::concat); #spanadd } #spanend #spanadd
-
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