JButton 子类将自身设置为 JFrame 的默认按钮
如何创建 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 );
}
}
How to create a subclass of JButton that makes itself the window's default button?
I understand that designating a default button is set on the JRootPane rather than the button itself. Instead of adding such code to each window, I would like to specify the default button by instantiating a subclass of JButton, "JButton_Default". The subclass should locate the JRootPane and set itself to be the default button.
I tried doing this in the subclass' constructor. Unfortunately, this approach works. I suppose that makes sense, as the button under construction is not yet an a form, so it cannot locate the JRootPane.
Is there some other way to program this JButton subclass?
Here's my subclass that fails:
import javax.swing.*;
public class JButton_Default extends JButton {
public JButton_Default() {
super();
JRootPane pane = this.getRootPane();
pane.setDefaultButton(this);
}
}
SOLVED ----------------
Here's the code for a JButton subsclass that makes itself the default button of the window to which it has been added.
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 );
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重写 JButton 类的 addNotify() 方法。我相信当组件添加到框架时会调用此方法。或者,如果这不起作用,则将 AncestorListener 添加到按钮并侦听 AncestorAdded 事件。
现在您知道该组件已添加到顶级容器中,因此您可以获得根窗格并将按钮设置为默认值。
Override the addNotify() method of your JButton class. I believe this method gets invoked when the component is added to a frame. Or if this doesn't work then add an AncestorListener to the button and listen for the ancestorAdded event.
Now you know the component is added to a top level container so you can get the root pane and set the button as the default.
您需要在构造函数中获取根窗格并将
this
添加到其布局中,否则您的按钮在构造时将不会有根窗格。You'll need to get the root pane in the constructor and add
this
to its layout, because otherwise your button won't have a root pane while it's being constructed.