[英]How to change the text color of a non-static JLabel? Java
我無法在JLabel中設置文本的顏色,我的程序是自動存儲塔。
代碼如下。 我是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的文本顏色更改為紅色?
謝謝您的幫助。
如錯誤所示,您不能在類(即“靜態上下文”)上調用非靜態方法。 因此,這是不允許的:
JLabel.setForeground(Color.red);
JLabel
引用該類,而不是它的特定實例。 該錯誤告訴您需要在JLabel
類型的對象上調用setForeground。 因此,創建一個JLabel
對象,然后使用方法設置其前景。
錯誤是指行
JLabel.setForeground(Color.red);
您必須准確地指定WHICH標簽。 例如
class Jukebox
{
private JLabel someLabel;
...
public Jukebox()
{
...
// JLabel.setForeground(Color.red); // Remove this
someLabel.setForeground(Color.RED); // Add this
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.