【问题标题】:How to create a custom JComponent (like a JButton) ignoring current Look and Feel如何创建忽略当前外观的自定义 JComponent(如 JButton)
【发布时间】:2017-03-01 11:43:09
【问题描述】:

我有一个具有默认外观和感觉 (insubstantial) 并设置了许多默认值的应用程序,例如:

    UIManager.put( "List.foreground", Color.BLACK );
    UIManager.put( xyz, zyzLEF );
//around 150 istructions like that

这个应用程序非常庞大,并且有许多根据客户需求量身定制的覆盖,但是现在我需要使用一些设置(ForegroundBackgroundFont 等)创建自己的 JButton 由于默认设置而无法按我的意愿行事(例如,setOpaque(true||false) 根本没有任何效果)。

所以我尝试创建自己的 JButton 忽略默认外观,例如:

public class MyButton extends JButton {
    public MyButton(String text, int lineHeight)
    {
        super(text);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        setBackground(Color.WHITE);
        //foo
        setOpaque(true);
    }

    @Override
    public String getUIClassID() {
        return "MyButton";
    }

在启动时:

UIManager.put("MyButton","javax.swing.plaf.ButtonUI");

这会导致这个错误:

UIDefaults.getUI() failed: createUI() failed for com.foo.MyButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=null,paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Hello World,defaultCapable=true] java.lang.reflect.InvocationTargetException
java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:732)
    at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)

我敢打赌,委托给 UIManger 是错误的,但我不知道如何忽略自定义项目的当前默认值。有什么想法吗?

感谢您的建议

【问题讨论】:

  • 为什么MyButton的类构造函数命名为JChatButton(String text, int lineHeight)
  • @A2H 在用通用摘要名称更改我的代码时错过了。固定
  • 我尝试不覆盖getUIClassID() 或只返回ButtonUI,我可以看到方法的变化:setOpaque, setFont, setBackgroun 等。这不是你想要完成的吗?
  • 是的,但是如果我按照你说的做,由于提到的默认值被覆盖,我什么也得不到
  • 据我了解,您正在使用自己的 L&F 设置一些自定义 JButtons 以及其他一些以保留默认 L&F?您能否创建并发布有效的minimal reproducible example 以及实际和所需输出的图像?这真的会帮助我理解你想要达到的目标。 This question 可能是相关的。 UIManager 不知道密钥 "MyButton" 这是有效密钥的list

标签: java swing look-and-feel


【解决方案1】:

你不能放这个

UIManager.put("MyButton","javax.swing.plaf.ButtonUI");

因为ButtonUI类(其实是ComponentUI类)的静态方法creatUI()会报错

public static ComponentUI createUI(JComponent c) {
        throw new Error("ComponentUI.createUI not implemented.");
    }

所以使用javax.swing.plaf.basic.BasicButtonUI

【讨论】:

    【解决方案2】:

    忽略当前的外观和感觉

    如果我了解您的要求,我认为最简单的方法是覆盖 JButton#updateUI() - 请参阅标签上的关闭按钮教程:

    private class TabButton extends JButton implements ActionListener {
        public TabButton() {
            //...
        }
    
        //we don't want to update UI for this button
        public void updateUI() {
        }
    

    【讨论】:

    • 谢谢,我会调查此事
    猜你喜欢
    • 2012-12-19
    • 2014-11-16
    • 2014-06-06
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多