在透明JFrame上绘制时不刷新背景

时间:2017-09-18 07:07:53

标签: java swing transparency

在透明窗口上绘画时,窗口未正确重新绘制,之前绘制的对象仍然显示。请参阅此示例(Ubuntu 14.04,1.8.0_141)。

案例1:我们通过透明的JFrame从透明的JPanel绘制图像。 案例2:我们直接在JFrame上绘制图像。

package test;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TranscluentWindow extends JFrame {
    /** The image we will draw on the frame **/
    private final BufferedImage test = generateImage();
    /** The location where to paint the image **/
    private Point p = new Point();
    /** Set up the GUI **/
    public TranscluentWindow() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setUndecorated(true);
        setExtendedState(MAXIMIZED_BOTH);
        setBackground(new Color(0, 0, 0, 0));
        //Disable this line for case 2
        setContentPane(new TranslucentPane());
        getContentPane().addMouseMotionListener(new MouseDragListener());
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TranscluentWindow().setVisible(true);
            }
        });
    }

    /** Move the image on the frame **/
    private class MouseDragListener extends MouseAdapter {
        @Override
        public void mouseMoved(MouseEvent e) {
            p = e.getPoint();
            repaint();
        }
    }

    /** Capture an image of any component **/
    private static BufferedImage getImage(Component c) {
        if(c==null) return null;
        BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        c.paint(g);
        return image;
    }

    /** Generates a dummy image to be painted on the frame **/
    private static BufferedImage generateImage() {
        JLabel label = new JLabel("test");
        label.setSize(label.getPreferredSize());
        return getImage(label);
    }

    //Enable these lines for case 2
//    public void paint(Graphics g) {
//        super.paint(g);
//        g.drawImage(test, p.x, p.y, this);
//    }

    public class TranslucentPane extends JPanel {
        public TranslucentPane() {
            setOpaque(false);
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            Graphics2D g2d = (Graphics2D) g.create();
//            g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
            g2d.setColor(new Color(0,0,0,0));
            g2d.fillRect(0, 0, getWidth(), getHeight());
            g2d.drawImage(test, p.x, p.y, this);
        }
    }    
}

代码的灵感来自this question

结果:

Result

0 个答案:

没有答案