如何创建使自己成为窗口默认按钮的 JButton 的子类?
我知道指定默认按钮是在 JRootPane 上设置的,而不是按钮本身。我不想将这样的代码添加到每个窗口,而是想通过实例化 JButton 的子类“JButton_Default”来指定默认按钮。子类应找到 JRootPane 并将其自身设置为默认按钮。
我尝试在子类的构造函数中这样做。不幸的是,这种方法有效。我想这是有道理的,因为正在构建的按钮还不是表单,所以它无法找到 JRootPane。
是否有其他方法可以对这个 JButton 子类进行编程?
这是我失败的子类:
import javax.swing.*;
public class JButton_Default extends JButton {
public JButton_Default() {
super();
JRootPane pane = this.getRootPane();
pane.setDefaultButton(this);
}
}
已解决 ------------------
下面是 JButton 子类的代码,它使自己成为添加它的窗口的默认按钮。
import javax.swing.*;
public class JButton_Default extends JButton {
@Override
public void addNotify() { // Upon being added to a window, make this JButton the default button of the window.
super.addNotify();
SwingUtilities.getRootPane( this ).setDefaultButton( this );
}
}
最佳答案
覆盖 JButton 类的 addNotify() 方法。我相信在将组件添加到框架时会调用此方法。或者,如果这不起作用,则将 AncestorListener 添加到按钮并监听 ancestorAdded 事件。
现在您知道组件已添加到顶级容器中,因此您可以获取根 Pane 并将按钮设置为默认按钮。
关于java - 将自身设置为 JFrame 的默认按钮的 JButton 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287145/