【问题标题】:changing background on JLabel shifts components改变 JLabel 的背景会改变组件
【发布时间】:2010-03-21 15:57:07
【问题描述】:

我使用的代码是:

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 看起来像这样:

之前: 后:

有什么想法吗?

【问题讨论】:

    标签: java user-interface swing background jlabel


    【解决方案1】:

    您为 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);
        }
    }
    

    【讨论】:

    • 你能提供一个paintComponent方法的例子吗?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2014-06-21
      相关资源
      最近更新 更多