首页 > 解决方案 > 奇怪的 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();
        }

标签: javaswingjframejpaneljcomponent

解决方案


通过覆盖 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);    

推荐阅读