Montag, 8. Oktober 2007

How to make a JPanel transparent?

The easy way is to change the alpha of the background Color:


public class TransparentPanel extends JPanel {


public TransparentPanel(){
}
/**
* Set the Transparency of the background color in %
*/
public void setTransparency(int d){
int newValue = (int) (d*2.55);
if (getBackground() != null ){
setBackground(new Color(getBackground().getRed(),getBackground().getGreen(),getBackground().getBlue(),newValue));
}
if (getParent() != null){
getParent().repaint();
}
}
public void setTransParent(){
setTransparency(100);
}
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
final TransparentPanel p = new TransparentPanel();
p.setBackground(Color.RED);
p.setPreferredSize(new Dimension(200, 100));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(p,BorderLayout.NORTH);
final JSlider slider = new JSlider(0,100,1);
frame.getContentPane().add(slider,BorderLayout.SOUTH);
slider.addChangeListener(new ChangeListener(){

@Override
public void stateChanged(ChangeEvent e) {
p.setTransparency(slider.getValue());
}
});
slider.setValue(100);
frame.setSize(200,200);
frame.setVisible(true);

}

}



Keine Kommentare: