Search code examples
javaswingtransparencyjradiobutton

How can I make JRadioButton transparent in particular case?


I have a couple of JRadioButton: rb1, rb2; which is contained in transparent JPanel p1, and p1 is contained in a colorful panel, named mainPanel. I want to make these JRadioButton transparent too and here is what I do:

in mainPanel: mainPanel.setBackground(Color.RED);

in p1: p1.setBackground(new Color(0,0,0,0));

and in rb1 and rb2:

rb1.setOpaque(false);
        rb1.setContentAreaFilled(false);
        rb1.setBorderPainted(false);
        rb2.setOpaque(false);
        rb2.setContentAreaFilled(false);
        rb2.setBorderPainted(false);

it's ok if rb1 and rb2 is contained in mainPanel or if p1 isn't a transparent JPanel, but in my case, the outcome is not what i expected: result

How can I resolve this problem? Thanks in advance!


Solution

  • The weird painting artifacts you're seeing are caused by this:

    p1.setBackground(new Color(0,0,0,0));
    

    With that the parent container will not be notified to clear it's background and repaint. So if you want the panel to be completely transparent, just use setOpaque(false) instead. You also just need to call this method on the radio buttons and nothing else.

    setOpaque will notify the parent to repaint, but if you want a semi-transparent panel, you have to override paintComponent and call super.paintComponent(Graphics) manually.

    enter image description here


    import java.awt.Color;
    import java.awt.EventQueue;
    
    import javax.swing.ButtonGroup;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    
    public class Example {
    
        public void createAndShowGUI() {    
            JRadioButton encryptButton = new JRadioButton("Encrypt");
            encryptButton.setOpaque(false);
    
            JRadioButton decryptButton = new JRadioButton("Decrypt");
            decryptButton.setOpaque(false);
    
            ButtonGroup group = new ButtonGroup();
            group.add(encryptButton);
            group.add(decryptButton);
    
            JPanel subPanel = new JPanel();
            subPanel.setOpaque(false);
            subPanel.add(encryptButton);
            subPanel.add(decryptButton);
    
            JPanel mainPanel = new JPanel();
            mainPanel.setBackground(Color.CYAN);
            mainPanel.add(subPanel);
    
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(mainPanel);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Example().createAndShowGUI();
                }
            });
        }
    
    }