【问题标题】:Set a different disabled color for two different JButtons? (UIManager.getDefaults changes both buttons)为两个不同的 JButton 设置不同的禁用颜色? (UIManager.getDefaults 更改两个按钮)
【发布时间】:2011-12-19 22:43:18
【问题描述】:

我正在尝试使一个按钮具有红色的禁用文本和蓝色的另一个禁用文本,但是当使用以下代码时,它所做的只是将它们都设为红色。

有没有简单的方法来解决这个问题?

UIManager.getDefaults().put("Button.disabledText",Color.BLUE);
button1.setEnabled(false);
UIManager.getDefaults().put("Button.disabledText",Color.RED);
button2.setEnabled(false);

【问题讨论】:

    标签: java swing colors jbutton


    【解决方案1】:

    外观由用户选择的外观中指定的ButtonUI 决定。如果您正在创建自己的 L&F,则可以覆盖 getDisabledTextColor()。这个相关的example 可能会建议如何进行。虽然这在技术上是可行的,但我不确定用户会如何解释这种差异。

    尽管与您的需求相切,JTextComponent 的后代为此提供​​了setDisabledTextColor()

    【讨论】:

    • “虽然它在技术上是可行的,但我不确定用户会如何理解这种差异。” 仅仅因为我们拥有这项技术,并不意味着我们应该使用它。
    • 当前JVM实例只有一个UIManager +1
    【解决方案2】:

    正如 thrashgod 所说,按钮的 ButtonUI 控制禁用的文本颜色。幸运的是,您可以更改按钮的ButtonUI

    button1.setUI(new MetalButtonUI() {
        protected Color getDisabledTextColor() {
            return Color.BLUE;
        }
    });
    button1.setEnabled(false);
    button2.setUI(new MetalButtonUI() {
        protected Color getDisabledTextColor() {
            return Color.RED;
        }
    });
    button2.setEnabled(false);
    

    【讨论】:

      【解决方案3】:
          /**
       * Sets the Color of the specified button.  Sets the button text Color to the inverse of the Color.
       *
       * @param button The button to set the Color of.
       * @param color The color to set the button to.
       */
      private static void setButtonColor(JButton button, Color color)
      {
          // Sets the button to the specified Color.
          button.setBackground(color);
          // Sets the button text to the inverse of the button Color.
          button.setForeground(new Color(color.getRGB() ^ Integer.MAX_VALUE));
      }
      

      这是我在上面找到的一些代码

      http://www.daniweb.com/software-development/java/threads/9791

      希望对你有帮助!!!我真的不明白这个问题:P

      【讨论】:

      • 我正在尝试在按钮被禁用时更改文本 (button.setEnabled(false))。我相信您给我的代码只会在启用按钮时影响颜色(button.setEnabled(true))。
      猜你喜欢
      • 2018-08-23
      • 1970-01-01
      • 2020-11-02
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多