Question

Le code J'utilise est:

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: text alt Après: text alt

Toutes les idées pourquoi?

Était-ce utile?

La solution

Vous donnez JLabel un fond qui est semi-transparent, mais vous avez indiqué qu'il est opaque. Cela signifie que Swing peignez pas les composants sous avant qu'il fournit JLabel avec l'objet graphique à utiliser pour le dessin. Le graphique fourni contient camelote qu'il attend JLabel écraser quand il tire son arrière-plan. Cependant, quand il tire son arrière-plan est semi-transparent de sorte que le reste indésirable.

Pour résoudre le problème, vous devez créer une extension de JLabel qui n'est pas opaque, mais a une méthode de paintComponent surchargée qui attirera 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);
    }
}

Autres conseils

Fond Avec La transparence 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top