自定义渐变按钮 - 无法看到文本

Tvd*_*Tvd 0 java swing gradient jbutton

我正在制作一个带有渐变效果的自定义按钮.我能够设置渐变效果,但我看不到文字.我哪里错了?

class CustomButton extends JButton {   
    Color color1, color2;   

    public CustomButton(String text, Color color1, Color color2) {   
        super(text);   
        this.color1 = color1;   
        this.color2 = color2;   
        setOpaque(false);   
        setSize(new Dimension(450, 350));
        setForeground(Color.white);
        setText(text);
        setContentAreaFilled(false);
    }   

    protected void paintComponent(Graphics g) {    
        super.paintComponent(g);
        int width = getWidth();   
        int height = getHeight();   

        GradientPaint paint = new GradientPaint(0, 0, color1, width, height,
                color2, true);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);   
        Paint oldPaint = g2d.getPaint();
        g2d.setPaint(paint);
        g2d.fillRect(0, 0, width, height);
        g2d.drawString("Button 1", getWidth()/2, 10);
        g2d.setPaint(oldPaint);
    }   
}  
Run Code Online (Sandbox Code Playgroud)

注意:我允许用户在运行时更改颜色.根据更改的颜色,我相应地设置背景.

kle*_*tra 5

正如斯坦已经回答的那样,解决方案的一部分是

button.setOpaque(false)
Run Code Online (Sandbox Code Playgroud)

按钮有点疯狂,他们想挤进去真的不画背景

button.setContentAreaFilled(false)
Run Code Online (Sandbox Code Playgroud)

要注意:确切的结果可能仍然高度依赖LAF - 看起来非常糟糕.对于基于synth(作为fi Nimbus),您可以考虑安装一个自定义Painter,配置渐变/颜色,由用户选择

编辑

只需仔细检查:

// tell ui to not paint the background
button.setOpaque(false);
button.setContentAreaFilled(false);

// override paintComponent
protected void paintComponent(...) {
     // do custom backgroudn painting
     ...
     // let ui handle the foreground (it wont touch the background due to the false settings above)
     super.paintComponent()
}
Run Code Online (Sandbox Code Playgroud)

适用于所有核心LAF(胜利时)