159

私のJPanelでは、 の背景をJLabel別の色に設定しました。「Test」という文字が見えて青くなっていますが、背景はまったく変化しません。どうすれば表示させることができますか?

this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
4

4 に答える 4

333

使用する

label.setOpaque(true);

opaqueのデフォルトはfalseforであるため、それ以外の場合、背景は描画されませんJLabel

JavaDocsから:

true の場合、コンポーネントは境界内のすべてのピクセルをペイントします。そうしないと、コンポーネントが一部またはすべてのピクセルを描画せず、下にあるピクセルが透けて見える可能性があります。

詳細については、Java チュートリアルラベルの使用方法 を参照してください。

于 2010-03-04T15:14:37.723 に答える
40

JLabel の背景はデフォルトで透明です。次のように不透明度を true に設定します。

label.setOpaque(true);
于 2010-03-04T15:16:05.997 に答える
15

setOpaque(true) を true に設定する必要があります。そうしないと、背景がフォームに描画されません。true に設定されていない場合、そのピクセルの一部またはすべてをフォームに描画することを読んでいると思います。背景はデフォルトで透明ですが、少なくとも私には奇妙に思えますが、プログラミングの方法では、以下に示すように true に設定する必要があります。

      JLabel lb = new JLabel("Test");
      lb.setBackground(Color.red);
      lb.setOpaque(true); <--This line of code must be set to true or otherwise the 

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()
于 2014-05-05T20:36:14.580 に答える
6

java.awt.Color背景については、パッケージにインポートしたことを確認してください。

mainメソッドで、つまりpublic static void main(String[] args)、すでにインポートされているメソッドを呼び出します。

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

注意: opaque を設定すると、可視性に影響します。Java では大文字と小文字が区別されることに注意してください。

于 2013-07-18T14:40:01.350 に答える