【发布时间】:2019-02-21 18:54:07
【问题描述】:
我有一些相同的扩展 JPanel 实例,每个实例都具有使用 Color(255, 255, 255, 0); 完成的透明背景。当任何 JPanel 的mousePressed() 被触发时,它的背景设置为纯色。
问题是,在鼠标按下后的最初几毫秒(懒人会克服它)背景变成了之前按下的 JComponent 的图像。
我希望有一些“内存清理器”或管理那些我不知道的 JComponent 操作的方法......
编辑:
addMouseListener(new MouseListener() {
boolean mousePressed;
public void mouseClicked(MouseEvent e) {}
Timer timer;
public void mousePressed(MouseEvent e) {
setBackground(new Color(255, 255, 255, 20));
setBorder(BorderFactory.createLineBorder(new Color(255, 255, 255, 100), 3));
repaint();
timer = new Timer();
mousePressed = true;
timer.scheduleAtFixedRate(new TimerTask() { //keep jpanel position relative to mouse position
Point pC = MouseInfo.getPointerInfo().getLocation();
Point pP = MouseInfo.getPointerInfo().getLocation();
Point sP = getLocation();
public void run() {
if(mousePressed) {
pC = MouseInfo.getPointerInfo().getLocation();
setLocation(sP.x + (pC.x - pP.x), sP.y + (pC.y - pP.y));
pP = pC;
sP = getLocation();
} else {
pC = MouseInfo.getPointerInfo().getLocation();
pP = MouseInfo.getPointerInfo().getLocation();
sP = getLocation();
}
}
}, 5, 5);
}
public void mouseReleased(MouseEvent e) {
mousePressed = false;
setBackground(null);
setBorder(null);
repaint();
timer.cancel();
}
【问题讨论】:
-
您能否与我们分享您的代码,以便我们无需猜测即可帮助您?
-
...each with transparent background ...Swing 不能正确处理透明背景。有关问题的解释和解决方案,请参阅:Backgrounds With Transparency。 -
这正是我一直在寻找的东西——知道问题出在哪里。感谢您发布的链接解决了它。谢谢!
标签: java swing jframe jpanel jcomponent