JToolBarでアイコンボタンを右寄せ

編集者:Terai Atsuhiro~

作成日:2006-01-23
更新日:2024-02-03 (土) 14:29:23
  • category: swing folder: ToolBarLayout title: JToolBarでアイコンボタンを右寄せ tags: [JToolBar, JMenuBar, BoxLayout, JButton, Focus] author: aterai pubdate: 2006-01-23T14:20:11+09:00 description: JToolBarでアイコンボタンを右寄せ、下寄せで表示します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTVb-HPZjI/AAAAAAAAAno/dMILsHzlipk/s800/ToolBarLayout.png

概要

JToolBarでアイコンボタンを右寄せ、下寄せで表示します。

概要

JToolBarでアイコンボタンを右寄せ、下寄せで表示します。

サンプルコード

#spanend
#spanadd
// jlfgr-1_0.jar
#spanend
#spanadd
String path = "/toolbarButtonGraphics/general/";
#spanend
#spanadd
URL url1 = getClass().getResource(path + "Copy24.gif");
#spanend
#spanadd
URL url2 = getClass().getResource(path + "Cut24.gif");
#spanend
#spanadd
URL url3 = getClass().getResource(path + "Help24.gif");
#spanend
#spanadd
toolbar.add(createToolbarButton(url1));
#spanend
#spanadd
toolbar.add(createToolbarButton(url2));
#spanend
#spanadd
toolbar.add(Box.createGlue());
#spanend
#spanadd
toolbar.add(createToolbarButton(url3));
#spanend
#spanadd
// ...
#spanend
#spanadd
private static JButton createToolbarButton(URL url) {
#spanend
  JButton b = new JButton(new ImageIcon(url));
  b.setRequestFocusEnabled(false);
  // or: b.setFocusPainted(false);
  return b;
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin

#screenshot

解説

  • JToolBarJMenuBarのデフォルトレイアウトはBoxLayoutのためBox.createGlue()を間に挟むことでボタンやメニューの右寄せが可能
  • ボタンとボタンの間隔を固定値で空けたい場合はBox.createRigidAreaを使用する
    • Box.createHorizontalStrut(...)Box.createVerticalStrut(...)を使うとツールバーの水平・垂直が切り替わった時に余計な余白が発生する場合がある
  • 各アイコンはJava look and feel Graphics Repositoryjlfgr-1_0.jarがクラスパス内に存在する場合はそこから読み込んでいる

サンプルコード

String path = "/toolbarButtonGraphics/general/";
URL url1 = MainPanel.class.getResource(path+"Copy24.gif");
URL url2 = MainPanel.class.getResource(path+"Cut24.gif");
URL url3 = MainPanel.class.getResource(path+"Help24.gif");
toolbar.add(new JButton(new ImageIcon(url1)));
toolbar.add(new JButton(new ImageIcon(url2)));
toolbar.add(Box.createHorizontalGlue());
toolbar.add(Box.createVerticalGlue());
toolbar.add(new JButton(new ImageIcon(url3)));
  • -
  • JDK 1.6JDK 1.5JToolBarに配置したボタン表示が異なる?
    • JComponent#setRequestFocusEnabled(false)(マウスクリックではフォーカスを取得しないがキーボードからは許可)、またはAbstractButton#setFocusable(false)と設定すると同一になる
  • &jnlp;
  • &jar;
  • &zip;
    ToolBarLayout1.png

解説

JToolBarはデフォルトの場合、BoxLayoutを使用するので、HorizontalGlueをアイコンボタンの間に挟むことで右寄せをしています。
  • マウスクリックでツールバーボタンにフォーカスが移動すると、コピーボタンを押したらテキストエディタでの文字列選択状態がクリアされたり、参考の質問のような不具合が起こる
  • 参考: Swing - JTextPane selection color problemの camickr さんの投稿(2008/10/25 0:34)
  • %JAVA_HOME%/demo/jfc/Notepad/src/Notepad.java
ツールバーが垂直になった場合のことも考えて、VerticalGlueも一緒に挿入していますが、特に問題ないようです。

参考リンク

アイコンは、Java look and feel Graphics Repositoryのjlfgr-1_0.jarから読み込んでいます。

コメント