我有一些相同的扩展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();
}
答案 0 :(得分:0)
通过覆盖 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);