简体   繁体   中英

How to change the text color of a non-static JLabel? Java

I can't set the color for the text within my JLabel, my program is a Jukebox.

The code is as follows. I'm fairly new to Java.

public Jukebox() {
    setLayout(new BorderLayout());
    setSize(800, 350);
    setTitle("Jukebox");


    // close application only by clicking the quit button
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    JPanel top = new JPanel();
    top.add(new JLabel("Select an option by clicking one of the buttons below"));
    add("North", top);
    top.setForeground(Color.RED);
    JPanel bottom = new JPanel();
    check.setBackground(Color.black);
    playlist.setBackground(Color.black);
    update.setBackground(Color.black);
    quit.setBackground(Color.black);
    check.setForeground(Color.red);
    playlist.setForeground(Color.red);
    update.setForeground(Color.red);
    quit.setForeground(Color.red);
    JLabel.setForeground(Color.red);
    bottom.add(check); check.addActionListener(this);
    bottom.add(playlist); playlist.addActionListener(this);
    bottom.add(update); update.addActionListener(this);
    bottom.add(quit); quit.addActionListener(this);
    bottom.setBackground(Color.darkGray);
    top.setBackground(Color.darkGray);
    add("South", bottom);

    JPanel middle = new JPanel();
    // This line creates a JPannel at the middle of the JFrame. 
    information.setText(LibraryData.listAll());
    // This line will set text with the information entity using code from the Library data import.
    middle.add(information);
    // This line adds the 'information' entity to the middle of the JFrame.
    add("Center", middle);

    setResizable(false);
    setVisible(true);
}

When I try to set the foreground color for the JLabel NetBeans IDE gives me an error detailing that I am unable to reference a non-static method from a static context.

What must I do to change the text color of my JLabel to red?

Thanks for the help.

As the error tells you, you can't call a non-static method on a class (which is the "static context"). So this is not allowed:

JLabel.setForeground(Color.red);

JLabel refers to the class and not to a particular instance of it. The error is telling you that setForeground needs to be called on an object of type JLabel . So make a JLabel object and then set its foreground with the method.

The error refers to the line

JLabel.setForeground(Color.red);

You have to specify WHICH label exactly you mean. For example

class Jukebox
{
    private JLabel someLabel;
    ...

    public Jukebox() 
    {
        ...
        // JLabel.setForeground(Color.red); // Remove this
        someLabel.setForeground(Color.RED); // Add this
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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