2014-02-06 27 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