2016-09-17 62 views
0

我有几个JRadioButton:rb1,rb2;它包含在透明JPanel p1中,而p1包含在一个名为mainPanel的彩色面板中。 我要让这些一个JRadioButton透明过,这里是我做的:如何在特定情况下让JRadioButton透明?

中的mainPanel:mainPanel.setBackground(Color.RED);

在P1:p1.setBackground(new Color(0,0,0,0));

,并在RB1和RB2:

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

它好的,如果rb1和rb2包含在mainPanel中,或者p1不是透明的JPanel,但在我的情况下,结果不是我所期望的:result

我该如何解决这个问题?提前致谢!

回答

4

你看到怪异的绘画文物是由这个原因引起:

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

随着父容器不会被通知来清除它的背景和重绘。因此,如果您希望面板完全透明,请改为使用setOpaque(false)。你也只需要在单选按钮上调用这个方法,而没有其他的。

setOpaque将通知父母重新绘制,但如果您想要半透明面板,则必须手动覆盖paintComponent并呼叫super.paintComponent(Graphics)

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(); 
      } 
     }); 
    } 

} 
+2

(1+)使用'setOpaque(...)'。对于需要半透明背景的情况,您还可以查看[背景透明度](https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/)。 – camickr

+0

非常感谢你。我习惯于采用透明的JLabel,但这不是一个正确的方法。再次感谢你,我的尊敬! –