2010-03-21 5 views
0

Le code J'utilise est:fond changeant sur les déplacements JLabel composants

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

Lorsque je clique sur le bouton pour changer les labales colorent l'interface graphique ressemble à ceci:

Avant: alt text http://www.freeimagehosting.net/uploads/67d741157b.png Après: alt text http://www.freeimagehosting.net/uploads/5cc86874fa.png

Des idées pourquoi?

Répondre

4

Vous attribuez au JLabel un arrière-plan semi-transparent, mais vous avez spécifié qu'il est opaque. Cela signifie que Swing ne peindra pas les composants sous-jacents avant de fournir à JLabel l'objet Graphics à utiliser pour le dessin. Le Graphics fourni contient des indésirables qu'il s'attend à ce que le JLabel écrase lorsqu'il dessine son arrière-plan. Cependant, quand il dessine son arrière-plan, il est semi-transparent de sorte que la camelote reste.

Pour résoudre le problème, vous devez créer une extension de JLabel qui n'est pas opaque mais qui a une méthode paintComponent substituée qui dessine l'arrière-plan que vous voulez.

EDIT: Voici un exemple:

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); 
    } 
} 
+0

pourriez-vous fournir un exemple de la méthode paintComponent? – Aly

3

Backgrounds With Transparency fournit la solution que vous avez accepté, mais vous fournit également une solution que vous pouvez utiliser sans étendre JLabel, ce qui pourrait intéresser.

Questions connexes