Swing/DividerSplitRatio のバックアップ(No.10)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/DividerSplitRatio へ行く。
- 1 (2011-11-14 (月) 11:39:46)
- 2 (2012-12-15 (土) 04:34:48)
- 3 (2014-10-25 (土) 23:50:32)
- 4 (2015-02-13 (金) 23:04:40)
- 5 (2016-10-21 (金) 19:29:22)
- 6 (2017-11-14 (火) 18:02:49)
- 7 (2019-06-18 (火) 19:20:05)
- 8 (2021-03-02 (火) 14:38:06)
- 9 (2024-12-29 (日) 22:08:01)
- 10 (2025-01-03 (金) 08:57:02)
- 11 (2025-01-03 (金) 09:01:23)
- 12 (2025-01-03 (金) 09:02:38)
- 13 (2025-01-03 (金) 09:03:21)
- 14 (2025-01-03 (金) 09:04:02)
- category: swing
folder: DividerSplitRatio
title: JSplitPaneのDividerの位置を最大化後に変更する
tags: [JSplitPane, JFrame, Divider]
author: aterai
pubdate: 2011-11-14T11:39:46+09:00
description: JFrameを最大化した後でJSplitPaneのDividerの位置を変更する場合のテストをします。
image:
概要
JFrame
を最大化した後でJSplitPane
のDivider
の位置を変更する場合のテストをします。
Screenshot

Advertisement
サンプルコード
class SplitPaneWrapper extends JPanel {
private int prevState = Frame.NORMAL;
private final JSplitPane splitPane;
protected SplitPaneWrapper(JSplitPane splitPane) {
super(new BorderLayout());
this.splitPane = splitPane;
add(splitPane);
EventQueue.invokeLater(() -> splitPane.setDividerLocation(.5));
}
private static int getOrientedSize(JSplitPane sp) {
return (sp.getOrientation() == JSplitPane.VERTICAL_SPLIT)
? sp.getHeight() - sp.getDividerSize()
: sp.getWidth() - sp.getDividerSize();
}
@Override public void doLayout() {
int size = getOrientedSize(splitPane);
final double proportionalLocation = splitPane.getDividerLocation() / (double) size;
super.doLayout();
int state = ((Frame) SwingUtilities.getWindowAncestor(splitPane)).getExtendedState();
if (splitPane.isShowing() && state != prevState) {
EventQueue.invokeLater(() -> {
int s = getOrientedSize(splitPane);
int iv = (int) Math.round(s * proportionalLocation);
System.out.format("DividerLocation: %d%n", iv);
splitPane.setDividerLocation(iv);
});
prevState = state;
}
}
}
View in GitHub: Java, Kotlin解説
MAXIMIZED_BOTH: keep the same splitting ratio
が未選択の場合:JSplitPane#setResizeWeight(0d)
に設定されているので、JFrame
をマウスでリサイズしても上コンポーネントの高さが維持される
MAXIMIZED_BOTH: keep the same splitting ratio
が選択されている場合:JSplitPane
をラップするJPanel
のdoLayout()
メソッドをオーバーライドして最大化、通常化の前後で上下コンポーネントの高さの比率を維持するEventQueue.invokeLater(...)
を使って後でJSplitPane#setDividerLocation(int)
でディバイダの位置を調節- デフォルト(
MAXIMIZED_BOTH: keep the same splitting ratio
チェックボックスのチェックを外している状態):- 例えば、最大化後にディバイダをすこし上に移動して
JFrame
を元に戻す(縮小)と上コンポーネントの方が下コンポーネントより高くなる
- 例えば、最大化後にディバイダをすこし上に移動して
JSplitPane#setDividerLocation(double)
は内部でJSplitPane#setDividerLocation(int)
を呼び出しているがその変換の際に値を切り捨てているので、このサンプルでは最大化、元に戻す(縮小)を行なっても同じ値になるように四捨五入するよう変更している
参考リンク
- JSplitPaneを等分割する
- java - How do you get JSplitPane to keep the same proportional location if the user has moved the location of the divider - Stack Overflow