Drawing over screen in Java

主宰稳场 提交于 2020-04-05 12:15:23

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/21604762/drawing-over-screen-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!