我想用 Java 创建一个帮助应用程序。其行为如下:每当通过全局快捷方式调用时,它都可以在屏幕上绘制一些文本(不是在其自己的应用程序窗口上,而是在屏幕顶部)。
类似的帖子是here https://stackoverflow.com/questions/3081204/draw-over-screen-with-quartz,但我想用Java实现这一点。
当我搜索“java在屏幕上绘制”之类的内容时,我只能得到很多关于Java2D的教程。
我想检查:1)是否可以在Java中绘制其他应用程序? 2)如果不可能,Mac / Ubuntu 中有其他替代方案吗?
多谢。
(旁注:我知道java没有全局快捷方式支持。我正在尝试其他方法来解决这个问题,这里不相关)
只需在屏幕上放置一个透明窗口并在其上绘图即可。透明窗口甚至支持点击,因此效果就像您直接在屏幕上绘图一样。
使用 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);
如果您的系统不支持每像素半透明度或不提供点击行为,您可以通过设置 Window 来尝试每像素透明度Shape
反而:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)