开发者

Swing: How to paint focus-rectangle just like current LAF?

开发者 https://www.devze.com 2022-12-28 16:10 出处:网络
This might be a long shot, but does anyone know of a way to paint the dotted line focus-rectangle on my custom component just like the current LAF compo开发者_JAVA技巧nents do?I\'m writing a custom co

This might be a long shot, but does anyone know of a way to paint the dotted line focus-rectangle on my custom component just like the current LAF compo开发者_JAVA技巧nents do? I'm writing a custom component and I would like it's UI delegate to look very much like the Windows 7 LAF. Thanks.


To paint a windows like dashed border use this Border class.

  import java.awt.Graphics;
  import java.awt.Insets;
  import javax.swing.UIManager;
  import javax.swing.border.Border;
  import java.awt.Component;


  public class DashedBorder implements Border {

    private static Insets EMPTY = new Insets(0,0,0,0);

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
      int vx, vy;

      g.setColor(UIManager.getDefaults().getColor("Button.focus"));

      // draw upper and lower horizontal dashes
      for (vx = x; vx < (x + width); vx += 2) {
        g.fillRect(vx, y, 1, 1);
        g.fillRect(vx, y + height - 1, 1, 1);
      }

      // draw left and right vertical dashes
      for (vy = y; vy < (y + height); vy += 2) {
        g.fillRect(x, vy, 1, 1);
        g.fillRect(x + width - 1, vy, 1, 1);
      }
    }

    @Override
    public Insets getBorderInsets(Component c) {
      return EMPTY;
    }

    @Override
    public boolean isBorderOpaque() {
      return false;
    }
  }


It will be tricky, but possible. E.g take a look to e.g. WindowsButtonUI. There is method called paintFocus and there are all information needed. As you can see the all values are read using UIManager.get*(string) methods where string is in form button.*. This is common convention used in UI defaults table.


Should be fairly easy by using appropriate BasicStroke and then creating a rectangualar shape using createStrokedShape method.

0

精彩评论

暂无评论...
验证码 换一张
取 消