简体   繁体   English

在 java 的 jlabel[] 中设置颜色值

[英]setting a color value in the jlabel[] in java

While I was writing a code, I found out that you can't do setColor to the Label I assigned.在编写代码时,我发现您无法对我分配的 Label 执行 setColor。 It tells me to put the length and put a variableDeclaration.它告诉我放长度并放一个variableDeclaration。 However, I do not know ho to do that.. How do you assign a font type or a color for "JLabel[] answerLabels;"?但是,我不知道该怎么做。你如何为“JLabel [] answerLabels;”分配字体类型或颜色?

    JLabel[] answerLabels;
    answerLabels = new JLabel[question.getAnswers().length]; 
    answerLabels.length[new Font("PT Serif",Font.BOLD,16)];

I recommend you to learn more about arrays.我建议您了解有关 arrays 的更多信息。

Look mate, you have an array(think of it as a list) of JLabel .看,伙计,您有一个JLabel数组(将其视为列表)。 Not a single JLabel没有一个JLabel

JLabel[] answerLabels;

The two square brackets [] after JLabel represent that you are creating an array, not a single JLabel . JLabel后面的两个方括号[]表示您正在创建一个数组,而不是单个JLabel

Therefore, when you call,因此,当你打电话时,

answerLabels = new JLabel[question.getAnswers().length]; 
answerLabels.length[new Font("PT Serif",Font.BOLD,16)];

you are not referring to a JLabel but you are referring to an array.您指的不是JLabel ,而是指数组。 Since, array doesn't have any methods such as, setForeground() or setFont() , your program will run into an error.由于数组没有任何方法,例如setForeground()setFont() ,因此您的程序将遇到错误。

So if you want to set the color or font of a particular JLabel , you have to refer to it.因此,如果要设置特定JLabel的颜色或字体,则必须参考它。 To refer to that JLabel , you have to write code as follows:要引用该JLabel ,您必须编写如下代码:

answerLabels[i].setForeground(Color.RED); 

Here, ' i ' represents the number of JLabel you want to access.这里,“ i ”代表您要访问的JLabel的数量。 Suppose, you want to access the third JLabel , then you have to write 2 in the place of 'i' in the above line.假设您要访问第三个JLabel ,那么您必须在上面一行中的 'i' 位置写 2。

Why 2, why not 3?为什么是2,为什么不是3? Because arrays start at 0.因为 arrays 从 0 开始。

Note that, the JLabel you are trying to access should be initialized before setting it's color or font by something like,请注意,您尝试访问的JLabel应该在设置它的颜色或字体之前进行初始化,例如,

answerLabels[i] = new JLabel();

Otherwise, your program will throw NullPointerException .否则,您的程序将抛出NullPointerException So, make sure to initialize the JLabel you are accessing from the array before setting it's color or font.因此,请确保在设置颜色或字体之前从数组中初始化您正在访问的JLabel

It looks like your trying to do something like this:看起来你试图做这样的事情:

    JLabel[] answerLabels = new JLabel[question.getAnswers().length];
    // This will loop through all of the JLabels and set the font and color
    for(int i=0; i<answerLabels.length; i++) {
        answerLabels[i] = new JLabel("Text from question/answer");
        answerLabels[i].setFont(new Font("PT Serif",Font.BOLD,16));
        answerLabels[i].setForeground(Color.red);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM