Java 在 OSX 上设置禁用 JButton 的颜色

Java set disable color of a JButton on OSX

您好,我正在尝试让多个按钮的禁用文本颜色因按钮而异。 我已经在 windows 中完成,但无法在 osx

中使用
class TestButton{
    
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setLayout(null);
        f.setBounds(0,0,600,600);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton b = new JButton();
        b.setBounds(0,0,80,80);
        f.add(b);

        b.setUI(new MetalButtonUI() {
            protected Color getDisabledTextColor() {
                return Color.RED;
            }
        });
        
        b.setEnabled(false);
        
        f.setVisible(true);
    }
}

我在 windows b.getUI returns MetalButtonUI 中看到,osx returns com.apple.laf.AquaButtonUI 但评估受到限制。 有办法做到吗? 谢谢

假设您希望 UI 组件在所有操作系统上看起来完全相同,请使用 'fixed' UI 制作您自己的组件。使用这个成语:

public class CustomButton extends JButton {
  public CustomButton() {
    setUI(new CustomButtonUI());
  }

  @Override
  public void updateUI() {
    // fixed UI
  }

  private static class CustomButtonUI extends BasicButtonUI {
    // ...
  }
}

从 Basic 或 Metal 扩展 UI 类.

通过用空主体重写 udpateUI 方法,您就避开了可插入的观感机制。