在Java中绘制屏幕

son*_*gyy 8 java drawing system

我想在Java中创建一个帮助应用程序..其行为类似于:通过全局快捷方式调用时,它可以在屏幕上绘制一些文本(而不是在其自己的应用程序窗口上,但在屏幕顶部).

类似的帖子在这里,但我想用Java实现这一点.

当我搜索"java draw over screen"之类的东西时,我只能获得很多关于Java2D的教程.

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

非常感谢.

(旁注:我知道java没有全局快捷方式支持.我正在尝试其他方法来解决这个问题,这里不相关)

Hol*_*ger 17

只需在屏幕上放置一个透明窗口并将其绘制到屏幕上即可.透明的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);
Run Code Online (Sandbox Code Playgroud)

如果不支持每像素半透明或不提供系统上的点击行为,则可以通过设置窗口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);
Run Code Online (Sandbox Code Playgroud)

  • @Tomas Bisciak:这不是"窗口",它有所不同.`w.setBackground(new Color(0,true));`安装alpha通道值为`0`的背景颜色.如果你在使它成为透明之前说'setUndecorated(true)`,那么它也适用于`Frame`.但我在这里使用"窗口",因此它不会显示在任务栏中. (2认同)