编辑(这不是导致问题的不透明属性,它正在更新 JLabel 的背景属性):我正在使用 MouseMotionListener 将 JLabel 的 setText() 设置为鼠标当前的位置。JLabel 在程序第一次运行时以正确的背景颜色/透明度开始。每当更新 text/mouseMotion 时,JLabel 就不再透明。
更新的可运行代码:
例如:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class MouseTester extends JFrame {
public static void main(String[] args) {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MouseTester.createMouseTester();
}
});
} catch (Throwable t) {
System.exit(1);
}
}
private static MouseTester mt = null;
private JLabel mouseLocation = null;
private static Color labelBackgroundColor = new Color(0, 0, 0, 127);
private static Color labelForegroundColor = Color.WHITE;
public static void createMouseTester() {
if (mt != null)
return;
mt = new MouseTester();
mt.setVisible(true);
}
private MouseTester() {
super();
mt = this;
setResizable(true);
Dimension dScreen = Toolkit.getDefaultToolkit().getScreenSize();
setMinimumSize(new Dimension(Math.min(800, dScreen.width), Math.min(590,
dScreen.height)));
setSize(getMinimumSize());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mouseLocation = new JLabel(" Lat/Long ");
mouseLocation.setOpaque(true);
mouseLocation.setBackground(labelBackgroundColor);
mouseLocation.setForeground(labelForegroundColor);
mouseLocation.setToolTipText("The MGRS coordinates.");
Component textArea = new TextArea("Move mouse here to see mouse motion info...");
// Add a mouse motion listener to capture mouse motion events
textArea.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent evt) {
TextArea source = (TextArea) evt.getSource();
// Process current position of cursor while all mouse buttons are up.
mouseLocation.setText(source.getText() + "\nMouse moved [" +
evt.getPoint().x + "," + evt.getPoint().y + "]");
mouseLocation.setBackground(labelBackgroundColor);
mouseLocation.setForeground(labelForegroundColor);
mouseLocation.setOpaque(true);
mouseLocation.repaint();
}
public void mouseDragged(MouseEvent evt) {
}
});
// Add the components to the frame; by default, the frame has a border layout
mt.add(textArea, BorderLayout.NORTH);
mouseLocation.setOpaque(true);
mouseLocation.setBackground(labelBackgroundColor);
mouseLocation.setForeground(labelForegroundColor);
mt.add(mouseLocation, BorderLayout.SOUTH);
int width = 300;
int height = 300;
mt.setSize(width, height);
}
}
JLabel 开始时透明/略带灰色,然后随着鼠标移动变为不透明且完全黑色。透明度由背景颜色决定。
我几乎尝试过在我能想到的任何地方更改背景颜色,但它不起作用..
我希望它一直保持颜色(它在启动时的颜色)。