Swing: How to draw focus rectangle the same as the current LAF?

It might be a long shot, but does anyone know a way to draw a dashed focus rectangle on my custom component in the same way as the current LAF components do? I am writing a custom component and I would like its delegate to be very similar to Windows 7 LAF. Thanks.

+2


a source to share


3 answers


Use this Border class to draw dashed windows.



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

      

+4


a source


It will be difficult, but possible. For example, take a look at for example WindowsButtonUI. There is a paintFocus method and all the information you need is there. As you can see, all values ​​are read using the methods UIManager.get*(string)

where it string

is in the form button.*

. This is the usual convention used in the default UI table.



+2


a source


Should be easy enough by using an appropriate BasicStroke and then creating a rectangular shape with createStrokedShape .

+1


a source







All Articles