2014-02-10 62 views
1

我无法为JLabel中的文本设置颜色,我的程序是Jukebox。如何更改非静态JLabel的文本颜色? Java

代码如下。我对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); 
} 

当我尝试设置前景色为JLabel的NetBeans IDE中给了我一个错误的细节,我无法从静态上下文引用非静态方法。

如何将我的JLabel的文本颜色更改为红色?

感谢您的帮助。

回答

1

正如错误告诉你的,你不能在一个类上调用非静态方法(这是“静态上下文”)。因此,这是不允许的:

JLabel.setForeground(Color.red); 

JLabel指的是类,而不是它的一个特定实例。错误是告诉你setForeground需要在JLabel类型的对象上调用。因此,制作一个JLabel对象,然后使用该方法设置其前景。

0

错误指的是线路

JLabel.setForeground(Color.red); 

你必须精确地指定你的意思是哪个标签。例如

class Jukebox 
{ 
    private JLabel someLabel; 
    ... 

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