我有一些相同的扩展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();
}
通过重写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);