Search code examples
javacolorsjlabel

Java change color JLabel


I know how to change a color in java from a JLabel object if you do it like this

JLabel label = new JLabel("label text");
label.setForeground(Color.red);

but::

i create my JLabes dynamic like this

center.add(new JLabel("Antwoord Vraag"+ (i +1) +": "+antwoord.get(i),SwingConstants.LEFT));

How could i change the color of a JLabel object without giving the object a name.


Solution

  • What you are looking for is a builder pattern for JLabel, which AFAIK does not exist. You can either create your own builder class, or extend JLabel with your own class that takes color as constructor argument (which is weird since JLabel has many properties, imagine what happens if each of them ahd it's own special constructor).

    JLabelBuilder example:

    public class JLabelBuilder {
        private Color fColor;
        private String text;
    
        public void setForegroundColor(Color c) {
            fColor = c;
        }
    
        public void setText(String t) {
            text = t;
        }
    
        public JLabel build() {
            if (text != null && fColor != null) {
                JLabel label = new JLabel(text);
                label.setForeground(fColor);
                return label;
            } else {
                ...
            }
        }
    }
    

    Usage:

    center.add(new JLabelBuilder()
                       .setText("Antwoord Vraag" + (i + 1) + ": " + antwoord.get(i))
                       .setForegroundColor(Color.red)
                       .build());
    

    Anyway, I don't see the harm in two more lines of code. Explicitly declaring your object variable is also a good practice for readability reasons. This will also work inside a loop:

    for(int i = 0 ; i < maxCounter ; i++) {
        String text = "Antwoord Vraag" + (i + 1) + ": " + antwoord.get(i);
        JLabel label = new JLabel(text, SwingConstants.LEFT);
        label.setForeground(Color.red);
        center.add(label);
    }