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

更改JLabel组件的背景

  •  0
  • Aly  · 技术社区  · 15 年前

    我使用的代码是:

    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();
        }
    }
    

    之前: alt text alt text

    2 回复  |  直到 6 年前
        1
  •  4
  •   Russ Hayward    15 年前

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

    编辑:下面是一个示例:

    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);
        }
    }
    
        2
  •  3
  •   camickr    15 年前

    Backgrounds With Transparency 提供了您接受的解决方案,但也提供了一个无需扩展JLabel即可使用的解决方案,这可能是您感兴趣的。

    推荐文章