java - 奇怪的 JPanel 背景故障
问题描述
我有一些相同的扩展 JPanel 实例,每个实例都有透明背景,使用Color(255, 255, 255, 0);
. 当mousePressed()
任何 JPanel 被触发时,它的背景设置为纯色。
问题是,在鼠标按下后的前几毫秒(懒惰的人会克服它),背景变成了 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();
}
解决方案
通过覆盖 paintComponent()
方法并将不透明设置为解决 false
JPanel panel = new JPanel();
protected void paintComponent(Graphics g)
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
panel.setOpaque(false); // background of parent will be painted first
panel.setBackground( new Color(255, 0, 0, 20) );
frame.add(panel);
推荐阅读
- azure-iot-hub - Iothub 消息路由到不同的 Azure 存储 Blob
- firemonkey - 数组的运行时分配 (C++, FMX)
- python - 非递归函数 follow_me(d, s) 其中 d 是字典,s 是字符串
- python - 无法让我的代码识别特定字符串
- postgresql - 从 jsonb 内的嵌套数组中选择数据
- javascript - 函数变量未正确传递给 setState
- javascript - 从 json 文件中过滤信息并通过链接显示 pdf
- typescript - vuex 类命名空间的属性不起作用,尽管我在模块中添加了 namespaced:true
- python-3.x - 如何识别熊猫假期前后的日子?
- javascript - 将 HTML 表单中的数据插入到 Kendo 网格数据中