• category: swing folder: HideActionText title: JButtonのテキストとしてActionの名前を適用しないよう設定する tags: [JButton, AbstractButton, Action] author: aterai pubdate: 2017-09-25T13:00:27+09:00 description: JButtonにActionを設定したとき、そのアクション名をJButtonのテキストとして適用しないよう設定します。 image: https://drive.google.com/uc?id=0ByeXYahiJNmHa2J2Q0xkT013OTA

概要

JButtonActionを設定したとき、そのアクション名をJButtonのテキストとして適用しないよう設定します。

サンプルコード

#spanadd
Action pasteAction = new DefaultEditorKit.PasteAction();
#spanend
#spanadd
pasteAction.putValue(Action.LARGE_ICON_KEY, new ColorIcon(Color.GREEN));
#spanend
#spanadd

#spanend
#spanadd
JButton button = new JButton("text");
#spanend
#spanadd
button.setFocusable(false);
#spanend
#spanadd
button.setAction(pasteAction);
#spanend
#spanadd
button.setIcon(new ColorIcon(Color.RED));
#spanend
#spanadd
button.addActionListener(e -> Toolkit.getDefaultToolkit().beep());
#spanend
#spanadd

#spanend
button.setHideActionText(false);
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JButton#setHideActionText(false)を設定した状態でActionを変更した場合などのテストを行っています。

  • JButton#setHideActionText(false)を設定した状態でActionを変更した場合、そのアクション名やアイコンなどはJButtonに適用されない
    • JButton.setText(...)JButton.setIcon(...)の設定が残る
  • JButton#setHideActionText(false)を設定した状態でも、Actionnull(初期状態)に変更するとJButtonのテキストやアイコンはクリアされてしまう
  • アクションから名前とアイコンが適用された状態でJButton#setHideActionText(false)を実行した場合、JButtonのテキストはクリアされるが、アイコンは変化しない
    • JButton.setText(...)JButton.setIcon(...)の設定が優先される
  • JButton#setHideActionText(false)を設定した状態でもActionnull(初期状態)に変更するとJButtonのテキストやアイコンはクリアされてしまう
  • アクションから名前とアイコンが適用された状態でJButton#setHideActionText(false)を実行した場合、JButtonのテキストはクリアされるがアイコンは変化しない
    • JButton.setText(...)JButton.setIcon(...)で設定している場合も同様にJButtonのテキストはクリアされるが、アイコンは変化しない
  • JButton#setHideActionText(...)の状態にJButton.setText(...)JButton.setIcon(...)は依存しない

参考リンク

コメント