2014-07-03 688 views
3

我想添加一個半透明的jPanel。但是放置在jPanel中的其他組件(例如按鈕和標籤)應該以100%不透明度顯示。我使用netbeans來設計GUI。通常,我將拖放組件拖放到調色板中以設計GUI(我不編碼它們)。我無法在屬性窗口中看到任何屬性來實現此目的。請幫幫我。由於我對Java很新,請給我一個詳細的答案。提前致謝。如何使jPanel半透明?

+5

贊[this](http://stackoverflow.com/a/2166500/230513)? – trashgod

回答

7

您可以使用 JPanel.setBackground(Color bg); 使面板半透明。顏色的屬性是什麼。 您可以使用alpha值構造顏色來設置顏色的透明度。

panel.setBackground(new Color(213,134,145,123));

最後一個參數是實際的alpha值,您可以調整它以查看效果。

下面是代碼:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics; 

import javax.swing.BorderFactory; 
import javax.swing.Box; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 

public class PanelTest { 
    public static void main(String[] args) { 

     Runnable runnable = new Runnable() { 
      @Override 
      public void run() { 
       PanelTest test = new PanelTest(); 
       test.createUI(); 
      } 
     }; 
     SwingUtilities.invokeLater(runnable); 
    } 

    public void createUI(){ 
     JFrame frame = new JFrame("Panel Test"); 

     JPanel panel = new JPanel(); 

     panel.setBackground(new Color(213, 134, 145, 123)); 
     JButton button = new JButton("I am a button"); 

     JLabel label = new JLabel("I am a label"); 
     label.setFont(new Font("Arial", Font.BOLD, 15)); 

     JTextField textField = new JTextField(); 

     panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
     panel.add(button); 
     panel.add(Box.createVerticalStrut(20)); 
     panel.add(label); 
     panel.add(Box.createVerticalStrut(20)); 
     panel.add(textField); 

     panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); 

     BottomPanel buttomPanel = new BottomPanel(); 
     buttomPanel.add(panel); 
     frame.add(buttomPanel,BorderLayout.CENTER); 

     frame.setResizable(false); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    @SuppressWarnings("serial") 
    class BottomPanel extends JPanel{ 
     @Override 
     protected void paintComponent(Graphics g) { 
      for (int y = 0; y < 200; y = y + 20) { 
       g.drawString("I am the string on the bottom", 5, y); 
      } 
     } 
    } 
} 

這裏是有效果的,希望它可以幫助你。

enter image description here

1

您可以簡單地創建使用拖放您的JPanel,因爲你總是這樣,然後改變面板的顏色,使之透明或半透明的,你可以使用此代碼:

panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f)); 

您可以通過更改Color構造函數的前三個參數(它們代表RGB)來更改顏色,並且可以通過更改第四個參數(即顏色的Alpha值)來更改透明度。