JToggleButton内に選択状態を同期したJRadioButtonを描画する
Total: 732, Today: 1, Yesterday: 2
Posted by aterai at
Last-modified:
Summary
JTobbleButton内に選択状態を同期したJRadioButtonと複数行テキストを描画してRadioCardを作成します。
Screenshot

Advertisement
Source Code Examples
private static Component makeRadioIconLayer(AbstractButton button) {
JRadioButton radio = new JRadioButton();
radio.setOpaque(false);
Dimension d = radio.getPreferredSize();
Insets i = button.getInsets();
button.setMargin(new Insets(i.top, d.width, i.bottom, i.right));
button.setPreferredSize(button.getPreferredSize());
button.setVerticalAlignment(SwingConstants.TOP);
LayerUI<AbstractButton> layer = new LayerUI<AbstractButton>() {
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
AbstractButton b = (AbstractButton) ((JLayer<?>) c).getView();
Graphics2D g2 = (Graphics2D) g.create();
radio.setSelected(b.isSelected());
int x = i.left - d.width + 8;
int y = i.top + 8;
SwingUtilities.paintComponent(
g2, radio, b, x, y, d.width, d.height);
g2.dispose();
}
}
};
return new JLayer<>(button, layer);
}
View in GitHub: Java, KotlinDescription
JTobbleButtonに<html>タグで複数行のテキストを設定してカードを作成JTobbleButtonにJLayerを設定してその左余白にJRadioButtonを描画JTobbleButtonにJLayerを適用するとその高さが一行分?まで縮小してしまう?JLayerを適用する前の推奨サイズをJTobbleButton#setPreferredSize(...)で設定してこれを回避- この回避方法は
LookAndFeelの変更には対応していない
LayerUI#paint(...)をオーバーライドしてSwingUtilities.paintComponent(...)でJRadioButtonを描画しているのでJRadioButtonのクリックは親のJTobbleButtonのクリックになるLayerUI#paint(...)内でradio.setSelected(toggle.isSelected())を実行してJRadioButtonとJTobbleButtonの選択状態が同期するよう設定
Reference
- OverlayLayoutの使用
OverlayLayoutでJRadioButtonとJTobbleButtonを重ねて配置する方法もある
- HTMLEditorKitを適用したJEditorPaneのフォームにコンポーネントを表示する
<input type='radio' ...>のようなhtmlタグでJRadioButtonを配置する方法もある?
- JRadioButtonのデフォルトアイコンをサムネイルに変更する