java如何在区域JPanel中创建半透明JPanel
我想制作一个半透明的JPanel
,我可以为它选择x坐标、y坐标、宽度和高度。我已经找到了一些材料,使半透明的JPanel
填充其父容器,但我不需要这种效果。我需要一个半透明的JPanel
,它的位置可以在父容器中指定,这样只有这个区域是半透明的,而父容器中的其他区域是不透明的。我试过这个代码,但不正确。合成的面积比我想要的面积小。怎么了,或者我怎样才能得到这种效果
public class TranslucentJPanel extends JPanel {
private float transparency;
public TranslucentJPanel(){
}
/**set the transparency
*
* @param transparency:the transparency you want to set
*
* @return void
*/
public void setTransparent(float transparency) {
this.transparency = transparency;
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D graphics2d = (Graphics2D) g.create();
graphics2d.setComposite(AlphaComposite.SrcOver.derive(transparency));
graphics2d.fill(getBounds());
graphics2d.dispose();
}
}
# 1 楼答案
所以,我马上想到两件事
首先,不要使用
getBounds
,因为Grapghics
上下文已经被转换为组件x
/y
位置,所以你要加倍。相反,只需使用0x0
并提供width
和height
,类似于另外,请记住,大多数Swing组件在默认情况下都是不透明的,这包括
JList
、JScrollPane
和JViewport
,如果希望它们完全透明,则需要将它们设置为透明此外,
JList
使用的“默认”渲染器也会将其自身渲染为不透明,因此如果希望项目透明,则需要能够提供自己的渲染器