Search code examples
javaswingimageiconjradiobutton

How can I keep the bubble from a JRadioButton when adding an ImageIcon?


I am improving a rock, paper, scissors program I created using swing, and now I'm adding ImageIcons for each JRadioButton. I imported and added rock, but I cannot seem to find a way to keep the bubble

enter image description here

that is shown next to the text. When I add the icon, I get this.

enter image description here

Any advice? Thanks!


Solution

  • "How can I keep the bubble from a JRadioButton when adding an ImageIcon?"

    Maybe you group the icons and the RBs into separate panels

    • Create a panel for each rock, paper, and scissors
    • Add the radio button and the label of the image to the panel
    • Add those panels to another panel to hold all three

    Something like this

    JRadioButton rock = new JRadioButton("Rock");
    JRadioButton paper = new JRadioButton("Paper");
    JRadioButton scissors = new JRadioButton("Scissors");
    
    ButtonGroup bg = new ButtonGroup();
    bg.add(rock);
    bg.add(paper);
    bg.add(scissors);
    
    JPanel rockPanel = new JPanel();                         <-- Rock panel
    rockPanel.add(rock);                                     <-- Rock RB
    rockPanel.add(new JLabel(new ImageIcon("rock.png"));     <-- Rock Icon
    
    JPanel paperPanel = new JPanel();                        <-- Paper Panel
    rockPanel.add(paper);                                    <-- Paper RB
    rockPanel.add(new JLabel(new ImageIcon("paper.png"));    <-- Paper Icon
    
    JPanel scissorsPanel = new JPanel();                     <-- Scissors Panel
    rockPanel.add(scissors);                                 <-- Scissors RB
    rockPanel.add(new JLabel(new ImageIcon("scissors.png")); <-- Scissors Icon
    
    JPanel holdThreePanel = new JPanel(new GridLayout(3, 1));
    holdThreePanel.add(rockPanel);                           <-- Rock Panel
    holdThreePanel.add(paperPanel);                          <-- Paper Panel
    holdThreePanel.add(scissorsPanel);                       <-- Scissors Panel
    

    Then you'll have something like this

            holdThreePanel
    --------------------------------
    |  O  Rock     [rock icon]     |
    |  O  Paper    [paper icon]    |
    |  O  Scissors [scissors icon] |
    +------------------------------+
    

    If you don't want the text, don't set any text to the RadioButton. JRadioButton rock = new RadioButton();