JToggleButtonが選択状態のときチェックアイコンを表示する
Total: 26
, Today: 26
, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JToggleButton
が選択状態の場合はチェックアイコンを表示し、非選択状態の場合はサイズが0
のアイコンを設定して非表示にします。
Screenshot
Advertisement
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, KotlinExplanation
JRadioButton
やJCheckBox
のように選択状態を表すチェックアイコンを常に表示するのではなく、JToggleButton
にActionListener
を追加して選択状態が変化したときにサイズの異なるチェックアイコンを設定することで選択状態の変化を表現するよう設定- このため選択状態が変化すると
JToggleButton
自体の幅も変化する - 選択状態のチェックアイコンはJCheckBoxのチェックアイコンを拡大縮小するで使用したアイコンの外枠を非表示にして使用
- このため選択状態が変化すると
- 各
JToggleButton
は選択背景色とLineBorder
の色を同じに設定 - 各
JToggleButton
はLineBorder
の幅である1px
で重なるよう設定したFlowLayout
を使用してJPanel
に配置
Reference
- JRadioButtonを使ってToggleButtonBarを作成
- JCheckBoxのチェックアイコンを拡大縮小する
- ButtonGroup中にある選択状態のJToggleButtonをクリックして選択解除可能にする