• category: swing folder: SwappingSplitPane title: JSplitPaneに設定した子コンポーネントの位置を入れ替える tags: [JSplitPane] author: aterai pubdate: 2019-01-21T00:29:34+09:00 description: JSplitPaneに設定した子コンポーネントの位置と余分なスペースの配分率を入れ替えます。 image: https://drive.google.com/uc?export=view&id=1TMNOHO7KVS63zeFEW4xasYw5TX-ZNqTL9w hreflang:
       href: https://java-swing-tips.blogspot.com/2019/01/swap-position-of-child-components-in.html
       lang: en

概要

JSplitPaneに設定した子コンポーネントの位置と余分なスペースの配分率を入れ替えます。

サンプルコード

JButton button = new JButton("swap");
button.setFocusable(false);
button.addActionListener(e -> {
  Component left = sp.getLeftComponent();
  Component right = sp.getRightComponent();

  // sp.removeAll(); // Divider is also removed
  sp.remove(left);
  sp.remove(right);
  // or:
  // sp.setLeftComponent(null);
  // sp.setRightComponent(null);

  sp.setLeftComponent(right);
  sp.setRightComponent(left);

  sp.setResizeWeight(1d - sp.getResizeWeight());
  if (check.isSelected()) {
    sp.setDividerLocation(sp.getDividerLocation());
  }
});
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、水平分割したJSplitPaneの左右に配置したコンポーネントを入れ替え可能に設定しています。

  • すでにJSplitPaneに配置されているコンポーネントを別の位置に配置すると例外が発生するため、一旦JSplitPaneから削除する必要がある
  • JSplitPane#removeAll()を使用するとディバイダも削除されてしまう
  • JSplitPane#remove(Component)、またはJSplitPane#setLeftComponent(null)などで削除する
  • ディバイダの位置を入れ替え前と同じ場所に保つ場合、JSplitPane#setResizeWeight(...)メソッドで余分なスペースの配分率の入れ替えと、JSplitPane#setDividerLocation(...)メソッドで位置の再設定が必要になる

参考リンク

コメント