这可能是一个冒险的尝试,但有没有人知道一种方法来绘制虚线焦点矩形在我的自定义组件上,就像当前的LAF组件一样?我正在编写一个自定义组件,希望它的UI代理看起来非常像Windows 7 LAF。谢谢。
要绘制类似虚线的边框,请使用 Border 类。
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;
}
}
这可能有些棘手,但是可以做到。例如,看一下WindowsButtonUI。那里有一个叫做paintFocus的方法,所有需要的信息都在那里了。正如您所看到的,所有值都是使用UIManager.get*(string)
方法读取的,其中string
的格式为button.*
。这是UI默认表中常用的约定。
使用适当的BasicStroke,然后使用createStrokedShape方法创建矩形形状,应该相当容易。
UIManager.getDefaults().getColor("Button.focus")
。我并不需要任何自定义绘制,所以我只是使用了从UIManager
获取的颜色来创建一个BorderFactory.createLineBorder
。 - LoKi