简体   繁体   中英

JFrame - Draw graphics over a transparent background?

I am trying to make an undecorated transparent JFrame, and then paint some graphics over it. If I extend JFrame, set undecorated to true, and override paint with, I can make a transparent JFrame. Like this:

public class MainFrame extends JFrame {
public static void main(String[] args) throws Exception {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainFrame frame = new MainFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}


public MainFrame() {
    setTitle("ASDF");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setUndecorated(true);
    setBounds(0, 0, 200, 200);      
}

public void paint(Graphics g){
    g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 20));
    g.drawString("ASDF", 100, 100);
}
}

The problem is that when I try drawing something on it, I can't clear what is drawn for another repaint. Like in this example, the text retains the background that was there when it was drawn. So if I move aa window behind the frame, it looks weird, because the frame itself has the old background. I tried AlphaComposite.Clear, but that only made a black background. What can I do?

If I extend JFrame, set undecorated to true, and override paint with, I can make a transparent JFrame.

I don't think so. You just paint without caring about the background, which is quickly lost. If you want to know how to make transparent windows in java use Stackoverflow: search for [java] transparent window . This should help you creating such a window, but this is quite a complicated task: Transparent Window

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM