سؤال

في JPanel, ، قمت بتعيين خلفية أ JLabel إلى لون مختلف. أستطيع أن أرى كلمة "اختبار" وهي زرقاء ، لكن الخلفية لا تتغير على الإطلاق. كيف يمكنني الحصول عليها لإظهار؟

this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
هل كانت مفيدة؟

المحلول

يستخدم

label.setOpaque(true);

وإلا فإن الخلفية غير مرسومة ، لأن الافتراضي لـ opaque هو false ل JLabel.

من Javadocs:

إذا كان هذا صحيحًا يرسم المكون كل بكسل داخل حدوده. خلاف ذلك ، لا يجوز للمكون أن يرسم بعض أو كل وحدات البكسل ، مما يسمح للبكسلات الأساسية بالظهور.

لمزيد من المعلومات ، اقرأ البرنامج التعليمي Java كيفية استخدام الملصقات.

نصائح أخرى

خلفية Jlabel شفافة بشكل افتراضي. اضبط العتامة في True مثل ذلك:

label.setOpaque(true);

يجب عليك تعيين setopaque (صواب) إلى أخرى حقيقية لن يتم رسم الخلفية على النموذج. أعتقد أنه من قراءة أنه إذا لم يتم ضبطه على أنه سوف يرسم بعضًا من وحدات البكسل أو لم يكن. الخلفية شفافة افتراضيًا والتي تبدو غريبة بالنسبة لي على الأقل ولكن في طريق البرمجة ، عليك تعيينها على 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()

للخلفية ، تأكد من استيرادك 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);

NB: سيؤثر تعيين غير شفاف على وضوحه. تذكر حساسية الحالة في جافا.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top