将JButton子类设置为JFrame的默认按钮 [英] JButton subclass that sets itself to be the default button for a JFrame

查看:82
本文介绍了将JButton子类设置为JFrame的默认按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建JButton的子类,使其成为窗口的默认按钮?

How to create a subclass of JButton that makes itself the window's default button?

我知道在JRootPane上设置了默认按钮,而不是按钮本身.与其将这样的代码添加到每个窗口中,我不希望通过实例化JButton的子类"JButton_Default"来指定默认按钮.子类应该找到JRootPane并将其自身设置为默认按钮.

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.

我尝试在子类的构造函数中执行此操作.不幸的是,这种方法行得通.我想这是有道理的,因为正在构建的按钮还不是一种表单,因此它无法找到JRootPane.

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.

还有其他方法可以对此JButton子类进行编程吗?

Is there some other way to program this JButton subclass?

这是我失败的子类:

import javax.swing.*;

public class JButton_Default extends JButton {
    public JButton_Default() {
        super();
        JRootPane pane = this.getRootPane();
        pane.setDefaultButton(this);
    }
}

已解决----------------

SOLVED ----------------

这是JButton子类的代码,该子类使自身成为添加了该窗口的窗口的默认按钮.

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 );
    }
}

推荐答案

重写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.

这篇关于将JButton子类设置为JFrame的默认按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆