JRadioButton: how to replace text by IconImage?

前端 未结 4 1671
不思量自难忘°
不思量自难忘° 2021-01-13 10:22

I want to replace the text in my radio button list by an icon.

I\'ve tried this:

rotateButton = new JRadioButton(rotateIcon.getImage());
4条回答
  •  遥遥无期
    2021-01-13 10:50

    I just reproduced your described behavior using this source:

    import java.awt.Image;
    import javax.swing.*;
    import javax.imageio.ImageIO;
    import java.net.URL;
    
    class RadioWithImage {
    
        public static void main(String[] args) throws Exception {
            URL url = new URL("http://www.gravatar.com/avatar/" +
                "a1ab0af4997654345d7a949877f8037e?s=128");
            Image image = ImageIO.read(url);
            final ImageIcon imageIcon = new ImageIcon(image);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JRadioButton radioButton = new JRadioButton("A.T.", imageIcon);
                    JOptionPane.showMessageDialog(null, radioButton);
                }
            });
        }
    }
    

    Where is the radio button 'selected' icon?

    It seems like a bug to me, though I cannot recall seeing a radio with an icon. How are they supposed to look?


    Time to reach into my 'box of hacks'.

    import javax.swing.*;
    
    class RadioWithImage {
    
        public static void main(String[] args) throws Exception {
            String url = "http://www.gravatar.com/avatar/" +
                "a1ab0af4997654345d7a949877f8037e?s=128";
            final String html = "";
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JRadioButton radioButton = new JRadioButton(html);
                    JOptionPane.showMessageDialog(null, radioButton);
                }
            });
        }
    }
    

    Radio Button with Image

    This technique will not work if:

    1. The use-case requires other types of icons (pressed, roll-over, selected etc.)
    2. The button is disabled (it will render incorrectly).

提交回复
热议问题