1

我正在尝试使用 Synth 实现自定义的“Steampunk”主题外观 - 基本上提供了 SynthStyle、SynthPainter 和 SynthStyleFactory 的自定义版本。

我没有使用任何 XML,即一切都是通过 Java API 完成的。一般来说,这工作得很好,实际上开始看起来相当不错。

但是,我遇到了一些“复合”组件,例如 JCheckBox。当在 SynthPainter 上调用 paintCheckBoxBackground() 时,坐标指的是 JCheckBox 覆盖的整个区域。

我应该如何确定在该区域的哪个位置需要分别绘制复选框图标和文本?

4

1 回答 1

1

好吧,mb以下将有所帮助(代码将放入与JCheckBox关联的自定义画家中):

public void paintCheckBoxBackground(SynthContext context, Graphics g, int x, int y, int w, int h){

    AbstractButton c = (AbstractButton) context.getComponent();
    String text = c.getText();
    Icon icon = c.getIcon();
    if (icon == null){
        icon = context.getStyle().getIcon(context, "CheckBox.icon");
    };        
    int iconTextGap = c.getIconTextGap();       

    Rectangle componentRect = new Rectangle();
    Rectangle iconR = new Rectangle();

    Insets insets = new Insets(0, 0, 0, 0);
    if (context.getRegion().isSubregion()){
        insets = context.getStyle().getInsets(context, insets);
    }
    else{
        insets = context.getComponent().getInsets(insets);
    }

    componentRect.x = insets.left;
    componentRect.y = insets.top;
    componentRect.width = c.getWidth() - (insets.left + insets.right);
    componentRect.height = c.getHeight() - (insets.top + insets.bottom);

    if (icon != null){
        iconR.x += componentRect.x;
        iconR.y += componentRect.y;
        iconR.width = icon.getIconWidth();
        iconR.height = icon.getIconHeight();

        g.setColor(Color.GREEN);
        g.fillRect(iconR.x, iconR.y, iconR.width, iconR.height);
    }
    if (text != null){
        g.setColor(Color.RED);
        int textPos = iconR.x + iconR.width + iconTextGap;
        g.fillRect(textPos, iconR.y, c.getWidth() - insets.right - textPos, componentRect.height);            
    }
}

请注意,这里只考虑最常见的情况(左右对齐,图标右侧的文本)。有关更复杂的案例处理,请参阅源代码SwingUtilities.layoutCompoundLabel

于 2010-07-09T15:35:28.010 回答