0

我正在使用的代码是:

public class Test extends JFrame implements ActionListener {

    private static final Color TRANSP_WHITE =
        new Color(new Float(1), new Float(1), new Float(1), new Float(0.5));
    private static final Color TRANSP_RED =
        new Color(new Float(1), new Float(0), new Float(0), new Float(0.1));
    private static final Color[] COLORS =
        new Color[]{TRANSP_RED, TRANSP_WHITE};
    private int index = 0;
    private JLabel label;
    private JButton button;

    public Test() {
        super();

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        label = new JLabel("hello world");
        label.setOpaque(true);
        label.setBackground(TRANSP_WHITE);

        getContentPane().add(label);

        button = new JButton("Click Me");
        button.addActionListener(this);

        getContentPane().add(button);

        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(button)) {
            label.setBackground(COLORS[index % (COLORS.length)]);
            index++;
        }
    }

    public static void main(String[] args) {
        new Test();
    }
}

当我单击按钮更改标签颜色时,GUI 如下所示:

之前: 替代文字 之后: 替代文字

任何想法为什么?

4

2 回答 2

4

您为 JLabel 提供了一个半透明的背景,但您已指定它是不透明的。这意味着 Swing 在为 JLabel 提供用于绘制的 Graphics 对象之前不会绘制它下面的组件。提供的 Graphics 包含垃圾,它希望 JLabel 在绘制背景时覆盖这些垃圾。但是,当它绘制背景时,它是半透明的,因此垃圾仍然存在。

要解决此问题,您需要创建一个不透明的 JLabel 扩展,但有一个覆盖的 paintComponent 方法,该方法将绘制您想要的背景。

编辑:这是一个例子:

public class TranslucentLabel extends JLabel {
    public TranslucentLabel(String text) {
        super(text);
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(graphics);
    }
}
于 2010-03-21T16:12:18.597 回答
3

Backgrounds With Transparency提供了您接受的解决方案,但也为您提供了无需扩展 JLabel 即可使用的解决方案,这可能会引起您的兴趣。

于 2010-03-21T19:10:44.110 回答