簡體   English   中英

如何改變JLabel顏色

[英]how to change JLabel color

我有改變JLabel顏色的問題。 我正在使用三個JLabel變量。 我將鼠標事件放在這個JLabel變量上。 我運行無一不是改變顏色,當我在entring鼠標JLabels 我的確是,當我在JLabel變量上輸入鼠標時,一個JLabel改變了顏色。

請解決這個問題。

    entry.addMouseListener(this);
    entry.setOpaque(true);
    profile.addMouseListener(this);
    profile.setOpaque(true);

    public void mouseClicked(MouseEvent mc)
    {


    }
    public void mouseEntered(MouseEvent me) 
    {
        entry.setBackground(color);
        profile.setBackground(color);
    }
    public void mouseExited(MouseEvent me) 
    {

    entry.setBackground(Color.white);
    profile.setBackground(Color.white);

   }
   public void mousePressed(MouseEvent mp) 
   {

   }
   public void mouseReleased(MouseEvent mr)
   {

   }

您的問題是方法setBackground() ,更改setForeground()

entry.addMouseListener(this);
entry.setOpaque(true);
profile.addMouseListener(this);
profile.setOpaque(true);

public void mouseClicked(MouseEvent mc)
{}

public void mouseEntered(MouseEvent me) 
{
    entry.setForeground(Color.red);
    profile.setForeground(Color.red);
}

public void mouseExited(MouseEvent me) 
{
    entry.setForeground(Color.white);
    profile.setForeground(Color.white);
}
public void mousePressed(MouseEvent mp) 
{}
public void mouseReleased(MouseEvent mr)
{}

不完全確定你在問什么......我認為你的問題是你有兩個標簽,當你將鼠標輸入其中一個標簽時,你只想讓那個標簽有一個紅色背景,而不是兩個。

為此,您可以使用e.getComponent()獲取觸發鼠標事件的標簽,然后僅為該標簽設置背景。 此外,您可能希望使用setBackground(null)重置背景顏色,因為底層框架的背景可能並不總是白色。 最后,您可以使用MouseAdapter類而不是MouseListener ,為您不需要的所有其他方法提供默認值(no-op)。

MouseListener ma = new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
        e.getComponent().setBackground(Color.RED);
    }
    public void mouseExited(MouseEvent e) {
        e.getComponent().setBackground(null);
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM