java 绘图,用Java在屏幕上绘图

本文介绍如何使用Java创建一个应用,通过全局快捷键在屏幕上绘制文本,不遮挡其他窗口。作者探讨了在Java中是否能跨应用绘图,并提供了在透明窗口上实现此功能的代码示例,适用于Mac和Ubuntu系统,以及可能的替代方案。
摘要由CSDN通过智能技术生成

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值