【问题标题】:how to change JLabel color如何更改 JLabel 颜色
【发布时间】:2014-02-19 08:09:27
【问题描述】:

我无法更改 JLabel 颜色。我正在使用三个JLabel 变量。我将鼠标事件放在这个JLabel 变量上。当我在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)
   {

   }

【问题讨论】:

  • 您的问题是什么?我不明白。顺便说一句,setForeground(color) 你想要什么?更改标签字体颜色。
  • 您是否在问为什么当您将鼠标移到其中 一个 标签上时,为什么 两个 标签会改变颜色?在这种情况下,请尝试me.getSource().setBackground(...)。
  • @tobias_k: 最好是getComponent() 而不是getSource(),否则你需要一个类型转换。但我认为你成功了。

标签: java swingutilities awr


【解决方案1】:

不完全确定您在问什么...我假设您的问题是您有 两个 标签,当您将鼠标输入其中一个标签时,您只需要 那个 em> 标签具有红色背景,而不是两者。

为此,您可以使用e.getComponent() 获取触发鼠标事件的标签,然后仅为该标签设置背景。此外,您可能希望使用setBackground(null) 重置背景颜色,因为底层框架的背景可能并不总是白色。最后,您可以使用MouseAdapter 类代替MouseListener,为您不需要的所有其他方法提供默认值(无操作)。

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

【讨论】:

    【解决方案2】:

    您的问题是方法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)
    {}
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 2011-06-15
      相关资源
      最近更新 更多