java – JPanel中的半透明组件
作者:互联网
我有从Myanel扩展的类MyPanel. MyPanel类具有JLabel组件,其中包含一个图标.
我的问题是如何在MyPanel类中绘制/渲染此JLabel组件以获得半透明效果(请参阅图标)(不创建xxxJLabel扩展JLabel类并覆盖paintComponents方法).
谢谢
解决方法:
一种方法是向JLabel提供半透明图像.这可以在调用setIcon()或类似函数之前使用标准标签完成,或者通过扩展JLabel并覆盖setIcon()方法来执行相同操作.
例如.第二种技术
码
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class TransparentIcon {
public static void main(String[] args) throws Exception {
String imgURL =
"http://www.gravatar.com/avatar/" +
"a1ab0af4997654345d7a949877f8037e";
final BufferedImage image = ImageIO.read(new URL(imgURL));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ImageIcon icon = new ImageIcon(image);
JPanel p = new JPanel(new GridLayout(2,3));
for (int ii=0; ii<6; ii++) {
TransparentLabel tl = new TransparentLabel();
tl.setOpacity((ii+1)/6f);
tl.setIcon(icon);
p.add(tl);
}
JOptionPane.showMessageDialog(null, p);
}
});
}
}
class TransparentLabel extends JLabel {
float opacity = 1f;
public void setOpacity(float opacity) {
this.opacity = opacity;
}
private Icon getTranslucentIcon(Icon icon) {
if (icon!=null) {
BufferedImage bi = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
AlphaComposite ac = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,
opacity);
g.setComposite(ac);
icon.paintIcon(this,g,0,0);
g.dispose();
return new ImageIcon(bi);
} else {
return null;
}
}
public void setIcon(Icon icon) {
super.setIcon( getTranslucentIcon(icon) );
}
}
更新
I just wonder how it can be done if i get Graphics of JLabel inside MyPanel class and change its visual appearance?
LabelRenderTest.java将JLabel渲染为BufferedImage,以便它可以用于paintComponent(Graphics)方法内的自定义渲染.
请注意:我不太了解JLabel在您的用例中的优势.我在该示例中使用它来呈现HTML.如果我只有一个图像,我会直接使用图像(例如Graphics.drawImage(Image,int,int,ImageObserver))并且永远不会创建标签.
标签:java,swing,jpanel,translucency 来源: https://codeday.me/bug/20190730/1577084.html