Come faccio a impostare un colore di sfondo JLabel?
Domanda
Nel mio JPanel
, ho impostato lo sfondo di un JLabel
ad un colore diverso. Posso vedere la parola "Test" ed è blu, ma lo sfondo non cambia affatto. Come posso ottenere per mostrare?
this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
Soluzione
Usa
label.setOpaque(true);
In caso contrario, lo sfondo non è dipinto, dal momento che il default di opaque
è false
per JLabel
.
JavaDocs :
Se fosse vero il componente dipinge ogni pixel all'interno dei suoi confini. In caso contrario, il componente non può dipingere alcuni o tutti i pixel, permettendo ai pixel sottostanti per mostrare attraverso.
Per ulteriori informazioni, leggere il Java Tutorial Come utilizzare etichette .
Altri suggerimenti
Il JLabel sfondo è trasparente per impostazione predefinita. Impostare l'opacità al vero così:
label.setOpaque(true);
È necessario impostare la setOpaque (true) true altri saggi lo sfondo non sarà dipinto al form. Credo che dalla lettura che se non è impostata su vero che dipingerà alcuni o nessuno dei suoi pixel alla forma. Lo sfondo è trasparente per default che sembra strano per me almeno, ma nel modo di programmare che si deve impostare a true come illustrato di seguito.
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
Dalle JavaDocs
setOpaque
public void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds. Otherwise,
the component may not paint some or all of its pixels, allowing the underlying
pixels to show through.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
Per lo sfondo, assicurarsi di aver importato java.awt.Color
nel pacchetto.
Nel tuo metodo main
, vale a dire public static void main(String[] args)
, chiamare il metodo già importato:
JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);
NB: Impostazione opaca influenzerà la sua visibilità. Ricordate la sensibilità caso in Java.