半透明的JLabel没有正确显示背景

我有以下几行:

label.setBackground(new java.awt.Color(0, 150, 0, 50)); 

我把它放在MouseAdapter中的mouseReleased方法中。

基本上,当我点击它时,我想让标签突出显示为半透明的绿色。

我在面板中有几个标签,都添加了这个MouseAdapter。

我的问题是:

– 当我点击标签时,它显示半透明的绿色,但它显示的是另一个JLabel的背景,而不是我点击的那个。

无论我点击哪个标签,它总是描绘相同标签的背景。

– 无论何时我点击一个标签,它都会重复相同的背景。 – 奇怪的是,每次点击JLabel时,绿色的不透明度似乎都会增加,就好像每次点击一个新的JLabel时,它都会将半透明的绿色涂在自身上。

关于发生了什么的任何提示? 我应该尝试在此发布SSCCE吗? 或者是否有一个我想念的简单答案。 我之前没有发布SSCCE的原因是我的代码很大并且分布在多个文件中,所以我必须首先修改它。

有关可能出现的问题和一些解决方案,请参阅透明度背景 。

Swing只有一个不透明或透明组件的概念,它本身并不知道如何处理不透明但具有半透明背景颜色的组件。 就Swing而言,该组件是不透明的,因此它不会绘制组件下面的内容。

通常情况下,我会提供一个alpha值,然后将其应用于纯色背景,但在此示例中,我只是用背景颜色填充背景,因此除非您提供半透明颜色,否则它将被填充纯色。

在此处输入图像描述

 import java.awt.Color; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestTranslucentLabel { public static void main(String[] args) { new TestTranslucentLabel(); } public TestTranslucentLabel() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } try { TranslucentLabel label = new TranslucentLabel("This is a translucent label"); label.setBackground(new Color(255, 0, 0, 128)); label.setForeground(Color.WHITE); JLabel background = new JLabel(); background.setIcon(new ImageIcon(ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Rampage_Small.png")))); background.setLayout(new GridBagLayout()); background.add(label); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(background); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException exp) { exp.printStackTrace(); } } }); } public class TranslucentLabel extends JLabel { public TranslucentLabel(String text, Icon icon, int horizontalAlignment) { super(text, icon, horizontalAlignment); } public TranslucentLabel(String text, int horizontalAlignment) { super(text, horizontalAlignment); } public TranslucentLabel(String text) { super(text); } public TranslucentLabel(Icon image, int horizontalAlignment) { super(image, horizontalAlignment); } public TranslucentLabel(Icon image) { super(image); } public TranslucentLabel() { super(); } @Override public boolean isOpaque() { return false; } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(getBackground()); g2d.fillRect(0, 0, getWidth(), getHeight()); super.paintComponent(g2d); g2d.dispose(); } } }