I want to create an helper application in Java.. which behaves like: whenever called through a global shortcut, it can draw some text on the screen (not onto its own application window, but on top of the screen).
A similar post is here, but I want to achieve this in Java.
When I search something like "java draw over screen", I can only get lots of tutorials about Java2D.
I want to check: 1) is it possible to draw over other applications in Java? 2) If not possible, is there any alternatives in Mac / Ubuntu?
Thanks a lot.
(Side note: I know java don't have the global shortcut support. I'm trying other methods to solve that problem, non-related here)
Simply lay a transparent Window over the screen and draw onto it. Transparent Windows even support click-through so the effect is like if you were drawing over the screen directly.
Using Java 7:
Window w=new Window(null)
{
@Override
public void paint(Graphics g)
{
final Font font = getFont().deriveFont(48f);
g.setFont(font);
g.setColor(Color.RED);
final String message = "Hello";
FontMetrics metrics = g.getFontMetrics();
g.drawString(message,
(getWidth()-metrics.stringWidth(message))/2,
(getHeight()-metrics.getHeight())/2);
}
@Override
public void update(Graphics g)
{
paint(g);
}
};
w.setAlwaysOnTop(true);
w.setBounds(w.getGraphicsConfiguration().getBounds());
w.setBackground(new Color(0, true));
w.setVisible(true);
If per-pixel translucency is not supported or does not provide the click-through behavior on your system, you can try per-pixel transparency by setting a Window Shape
instead:
Window w=new Window(null)
{
Shape shape;
@Override
public void paint(Graphics g)
{
Graphics2D g2d = ((Graphics2D)g);
if(shape==null)
{
Font f=getFont().deriveFont(48f);
FontMetrics metrics = g.getFontMetrics(f);
final String message = "Hello";
shape=f.createGlyphVector(g2d.getFontRenderContext(), message)
.getOutline(
(getWidth()-metrics.stringWidth(message))/2,
(getHeight()-metrics.getHeight())/2);
// Java6: com.sun.awt.AWTUtilities.setWindowShape(this, shape);
setShape(shape);
}
g.setColor(Color.RED);
g2d.fill(shape.getBounds());
}
@Override
public void update(Graphics g)
{
paint(g);
}
};
w.setAlwaysOnTop(true);
w.setBounds(w.getGraphicsConfiguration().getBounds());
w.setVisible(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With