副predefined行动,关​​闭按钮的Java的JDialog [英] Associate predefined action to close button Java JDialog

查看:154
本文介绍了副predefined行动,关​​闭按钮的Java的JDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个包中的JDialog定义的操作。我要绑定在Java Dialog`s关闭按钮,这个动作,而无需使用窗口听众。只需设置一次,这个动作的按钮。你能不能帮我做这件事,好吗?谢谢

I have an action defined in the same package as the JDialog. I want to bind the Java Dialog`s close button to this action, without using window listeners. Just set once this action to the button. Can you help me do this, please? Thank you

推荐答案

默认情况下摇摆将使用操作系统的部件在运行上,这样你就不能访问该按钮,因为它不是一个Swing组件。

By default Swing will use the widgets of the OS you are running on so you don't have access to the button since it is not a Swing component.

如果你想使用Swing LAF即可进入关闭按钮,您的ActionListener添加到按钮。在code将是:

If you want to use the Swing LAF then you can access the close button and add your ActionListener to the button. The code would be:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DialogCloseAction
{
    private static void createAndShowGUI()
    {
        JDialog.setDefaultLookAndFeelDecorated(true);
        JDialog dialog = new JDialog();
        dialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
        dialog.setSize(200, 200);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible( true );

        Action close = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("closing...");
            }
        };

        JButton button = SwingUtils.getDescendantOfType(
            JButton.class, dialog.getRootPane(), "Icon", UIManager.getIcon("InternalFrame.closeIcon"));
        button.addActionListener( close );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

您需要使用达里尔的摇摆utils的类搜索框自定义按钮。

You will need to use Darryl's Swing Utils class to search the frame for the custom button.

否则,已经有人建议,你需要使用的WindowListener 。如果你愿意,你可以检查出关闭应用程序里面有一个简单的API,可让您的操作添加到自定义的 CloseListener

Otherwise, as has already been suggested, you will need to use a WindowListener. If you want you can check out Closing an Application which has a simple API that allows you to add an Action to the custom CloseListener.

这篇关于副predefined行动,关​​闭按钮的Java的JDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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