我正在创建自定义Swing组件,并希望提供一个看起来像Nimbus的UI
。
我知道如何访问UIDefaults
颜色,但是我可以重复使用更多代码吗?特别是,有没有办法让对象绘制聚焦环(矩形或椭圆形,或者更好,沿着任何轮廓Shape
),就像其他Nimbus组件一样? (没有重新发明轮子)
答案 0 :(得分:0)
由于我没有看到Nimbus中的任何设计决定允许重新使用画面来构建新组件,而且我仍然坚持使用Java 6和Nimbus作为移动(命名空间)目标的OS X,这是我的解决方案这基本上重现了Synth风格的用法:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class NimbusFocusBorder implements javax.swing.border.Border {
private static final RoundRectangle2D rect = new RoundRectangle2D.Float();
private static final Area area = new Area();
private final float arcIn;
private final float arcOut;
public NimbusFocusBorder() {
arcIn = arcOut = 0f;
}
public NimbusFocusBorder( float rounded ) {
arcIn = rounded * 2;
arcOut = arcIn + 2.8f;
}
public void paintBorder( Component c, Graphics _g, int x, int y, int w, int h ) {
if( !c.hasFocus() ) return;
final Graphics2D g = (Graphics2D) _g;
g.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
g.setColor( /* NimbusHelper. */ getFocusColor() );
rect.setRoundRect( x + 0.6, y + 0.6, w - 1.2, h - 1.2, arcOut, arcOut );
area.reset();
area.add( new Area( rect ));
rect.setRoundRect( x + 2, y + 2, w - 4, h - 4, arcIn, arcIn );
area.subtract( new Area( rect ));
g.fill( area );
}
public Insets getBorderInsets( Component c ) {
return new Insets( 2, 2, 2, 2 );
}
public boolean isBorderOpaque() { return false; }
// this actually looks up the color in UIDefaults
// in the real implementation
private Color getFocusColor() { return new Color( 115, 164, 209, 255 );}
}