JColorChooser定制-我们如何为JColorChooser设置渐变背景

时间:2018-11-15 14:17:59

标签: java swing paint jcolorchooser

我正在为JColorChooser设置渐变背景。基本上,我试图扩展BasicColorChooserUI类,然后重写PaintComponents方法。但是对ColorChooser无效。

public class AseColorChooserUI extends BasicColorChooserUI {

protected JColorChooser chooser;

JTabbedPane tabbedPane;
JPanel singlePanel;

JPanel previewPanelHolder;

private static final Color COLOR_0 = new Color(200, 200, 255);
private static final Color COLOR_1 = Color.BLUE;

protected AbstractColorChooserPanel[] defaultChoosers;

JComponent previewPanel;
public static ComponentUI createUI(JComponent c) {
    return new AseColorChooserUI();
}


public void installUI( JComponent c ) {
    chooser = (JColorChooser)c;

    super.installUI( c );
    chooser.getPreviewPanel().setOpaque(false);

    defaultChoosers = createDefaultChoosers();
    chooser.setChooserPanels(defaultChoosers);

    installDefaults();

    Component[] comps = chooser.getComponents();
    recursiveTransparent(comps);

}

protected void installDefaults() {
    LookAndFeel.installColorsAndFont(chooser, "ColorChooser.background",
                                          "ColorChooser.foreground",
                                          "ColorChooser.font");
    LookAndFeel.installProperty(chooser, "opaque", Boolean.FALSE);


}

private void recursiveTransparent(Component[] comps) {
    for (Component comp : comps) {
        if (comp instanceof JComponent && !(comp instanceof JList)) {
            ((JComponent) comp).setOpaque(false);
        }
        if (comp instanceof Container) {
            Component[] subComps = ((Container) comp).getComponents();
            recursiveTransparent(subComps);
        }
        if (comp instanceof JButton) {
            Component[] subComps = ((Container) comp).getComponents();
            recursiveTransparent(subComps);
        }
    }
}

protected void paintComponent(Graphics g, JComponent c) {
    super.paint(g,c);
    Graphics2D g2 = (Graphics2D) g;
    Point p0 = new Point(0, 0);
    Point p1 = new Point(chooser.getWidth(), chooser.getHeight());
    Paint paint = new GradientPaint(p0 , COLOR_0, p1, COLOR_1);
    g2.setPaint(paint);
    g2.fillRect(0, 0, p1.x, p1.y);
}

}

可以通过任何方式设置JColorChooser及其组件的渐变背景。

0 个答案:

没有答案