Drawing over screen in Java

后端 未结 1 916
失恋的感觉
失恋的感觉 2020-12-30 11:06

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 applica

相关标签:
1条回答
  • 2020-12-30 11:35

    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);
    
    0 讨论(0)
提交回复
热议问题