• category: swing folder: CheckButtonToggleGroup title: JToggleButtonが選択状態のときチェックアイコンを表示する tags: [JToggleButton, ButtonGroup, FlowLayout, Icon, ] author: aterai pubdate: 2025-02-03T00:41:02+09:00 description: JToggleButtonが選択状態の場合はチェックアイコンを表示し、非選択状態の場合はサイズが0のアイコンを設定して非表示にします。 image: https://drive.google.com/uc?id=1Hgu-Ti6Y0aB6H181Lwr9ZxQ59wE3nkgv

Summary

JToggleButtonが選択状態の場合はチェックアイコンを表示し、非選択状態の場合はサイズが0のアイコンを設定して非表示にします。

Source Code Examples

private static AbstractButton makeCheckToggleButton(String title) {
  AbstractButton b = new JToggleButton(title) {
    @Override public void updateUI() {
      super.updateUI();
      setBackground(Color.GRAY);
      setBorder(makeBorder(getBackground()));
      setContentAreaFilled(false);
      setFocusPainted(false);
      setOpaque(false);
    }
  };
  b.addActionListener(e -> {
    Container parent = ((AbstractButton) e.getSource()).getParent();
    SwingUtils.descendants(parent)
        .filter(AbstractButton.class::isInstance)
        .map(AbstractButton.class::cast)
        .forEach(MainPanel::updateButton);
  });
  return b;
}

private static void updateButton(AbstractButton button) {
  if (button.getModel().isSelected()) {
    button.setIcon(SELECTED_ICON);
    button.setForeground(Color.WHITE);
    button.setOpaque(true);
  } else {
    button.setIcon(EMPTY_ICON);
    button.setForeground(Color.BLACK);
    button.setOpaque(false);
  }
}
View in GitHub: Java, Kotlin

Explanation

  • JRadioButtonJCheckBoxのように選択状態を表すチェックアイコンを常に表示するのではなく、JToggleButtonActionListenerを追加して選択状態が変化したときにサイズの異なるチェックアイコンを設定することで選択状態の変化を表現するよう設定
  • JToggleButtonは選択背景色とLineBorderの色を同じに設定
  • JToggleButtonLineBorderの幅である1pxで重なるよう設定したFlowLayoutを使用してJPanelに配置

Reference

Comment