編集(問題を引き起こしているのは不透明な属性ではなく、JLabelの背景属性を更新しています):マウスの現在の位置が何であれ、JLabelのsetText()にMouseMotionListenerを使用しています。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 は透明/わずかにグレーで始まり、マウスの動きによって透明ではなく完全に黒に変わります。透明度は背景色で決まります。
思いついた場所の背景色を変更しようとしましたが、うまくいきません..
ずっと色のままにしたい(起動時の色)。