I want to create an overlay in Java that is transparent, always on top, and that I can click-through. I've found some similar posts about this issue, but even after following their answers, I'm having one issue.
My problem is making the whole window click-through. I'm not having any problem making it work with a JFrame, but once I add any components to it (JLabel or an ImagePanel), the click-through attribute doesn't carry over to them.
As I want to have a background image for my application this basically makes the code I have useless seeing how the window gets focused whenever I click the area the text/image covers.
Before I show the code I'm using I'd first like to refer to these threads which essentially describes precisely what I want, except in C#.
My goal is to create an overlay with a transparent .png-image and some text on-top that will change on key events. If it uses JFrame or any other library doesn't matter. I only need it compatible with Windows.
I'd also like to mention that I've got some experience with Java, but am a novice in using JFrame.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import com.sun.jna.platform.WindowUtils;
public class Overlay {
public static void main(String[] args) {
JFrame frame = new JFrame("Overlay Window");
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);
frame.setLocation(400, 400);
frame.getContentPane().setLayout(new java.awt.BorderLayout());
JLabel textLabel = new JLabel("I'm a label in the window", SwingConstants.CENTER);
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
frame.pack();
System.setProperty("sun.java2d.noddraw", "true");
WindowUtils.setWindowTransparent(frame, true);
WindowUtils.setWindowAlpha(frame, 1.0f);
//Using AWTUtilities gives the same result as WindowUtils
//AWTUtilities.setWindowOpaque(frame, false);
//AWTUtilities.setWindowOpacity(frame, 1.0f);
frame.setVisible(true);
}
}
Note that the problem is not about the window being focused (though that is a result of the issue), but about the JLabel and ImagePanel not being click-through.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…