Swing/GetComponentsRecursively のバックアップ(No.17)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/GetComponentsRecursively へ行く。
- 1 (2017-02-06 (月) 16:08:58)
- 2 (2017-02-07 (火) 12:54:52)
- 3 (2017-02-07 (火) 19:03:12)
- 4 (2017-02-20 (月) 19:40:38)
- 5 (2017-02-28 (火) 17:51:53)
- 6 (2017-03-07 (火) 14:31:16)
- 7 (2018-01-07 (日) 18:29:32)
- 8 (2018-02-15 (木) 14:23:42)
- 9 (2019-05-22 (水) 19:35:38)
- 10 (2020-01-02 (木) 19:28:25)
- 11 (2020-05-04 (月) 17:09:12)
- 12 (2021-10-31 (日) 01:08:58)
- 13 (2022-12-30 (金) 01:45:38)
- 14 (2024-02-26 (月) 13:39:27)
- 15 (2025-01-03 (金) 08:57:02)
- 16 (2025-01-03 (金) 09:01:23)
- 17 (2025-01-03 (金) 09:02:38)
- 18 (2025-01-03 (金) 09:03:21)
- 19 (2025-01-03 (金) 09:04:02)
- 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?id=1NedWhPhVuMDTwrHRaFdW-YXZjdH-019yuw
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, Kotlin解説
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; }
参考リンク
- JFileChooserのデフォルトをDetails Viewに設定
- JFileChooserでの隠しファイルの非表示設定を変更する
- Get All Components in a container : Container « Swing JFC « Java