2016-09-17 18 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,但這不是一個正確的方法。再次感謝你,我的尊敬! –

相關問題