代码之家  ›  专栏  ›  技术社区  ›  mikera

在自定义Synth外观中控制复选框的布局

  •  1
  • mikera  · 技术社区  · 14 年前

    我正在尝试使用Synth实现一个定制的“蒸汽朋克”主题的外观和感觉——基本上提供SynthStyle、SynthPainter和SynthStyleFactory的定制版本。

    我没有使用任何XML,也就是说,一切都是通过JavaAPI完成的。一般来说,这是工作刚刚好,实际上开始看起来相当体面。

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

    1 回复  |  直到 14 年前
        1
  •  1
  •   Taisin    14 年前

    好吧,下面这些会有帮助的 (代码将放入与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