2014-02-06 106 views
6

我想用Java创建一个辅助应用程序,其行为如下:无论何时通过全局快捷方式调用,它都可以在屏幕上绘制一些文本(而不是在它自己的应用程序窗口上,但是在屏幕)。用Java在屏幕上画图

一个类似的帖子是here,但我想在Java中实现这一点。

当我搜索诸如“java draw over screen”之类的东西时,我只能获得很多关于Java2D的教程。

我想检查:1)是否有可能在Java中绘制其他应用程序? 2)如果不可能,Mac/Ubuntu中是否有其他选择?

非常感谢。

(附注:我知道的java没有全局快捷键支持,我想其他的方法来解决这个问题,在这里不相关)

+0

行不通的。也许与平台相关的JNI。但没有纯粹的Java方法;这是肯定的。 –

回答

13

只要打好在屏幕上的透明窗口,绘制到它上面。透明的Windows甚至支持点击,因此效果就像直接在屏幕上绘画一样。

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

如果每个像素的透明度不支持或不提供系统上的点击行为,你可以通过设置窗口尝试每个像素的透明度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); 
+0

Thx for reply :)我还没有安装Java7 ..当我尝试使用Java6时,我有一个完全黑色的背景。无论如何设置Java 6的透明背景? – songyy

+0

@Holger请问您能指出这是透明吗?我知道它的工作原理并不清楚它为什么表现透明。这个* window *如何与JFrame不同? –

+0

从[Java SE 6 Update 10](http://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html#6u10)开始,您可以使用'com.sun.awt.AWTUtilities.setWindowOpaque(w ,假)'。只要在setVisible(true)之前调用它即可;' – Holger