1

我正在构建一个 NetBeans 平台应用程序。当用户单击主窗口的 X 时,我希望应用程序不执行任何操作并显示密码 JDialog。如果密码正确关闭应用程序,否则不要关闭应用程序。我该怎么做呢?我创建了一个将显示密码 JDialog 的 Listener 类,但是如何阻止应用程序关闭?类似于 JFrame 的 setDefaultCloseOperation,并将其设置为关闭时不执行任何操作。

    public class Listener extends WindowAdapter {

        private Frame frame;

        @Override
        public void windowActivated(WindowEvent event) {
            frame = WindowManager.getDefault().getMainWindow();
            frame.setSize(946, 768);
        }

        @Override
        public void windowClosing(WindowEvent event) {
            ShutDownMainWindowJDialog shutDownMainWindowJDialog;
            shutDownMainWindowJDialog = new ShutDownMainWindowJDialog(null, true);
            shutDownMainWindowJDialog.exeShutDownMainWindowJDialog();
            shutDownMainWindowJDialog.setLocationRelativeTo(frame);
            shutDownMainWindowJDialog.setVisible(true);
        }
    }

public class Installer extends ModuleInstall {

    @Override
    public void restored() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Frame frame = WindowManager.getDefault().getMainWindow();
                frame.addWindowListener(new Listener());
            }
        });
    }
}
4

2 回答 2

4

这很容易。因此,使用安装程序创建模块并覆盖方法关闭(可能),然后显示您的对话框并返回 false(不关闭应用程序)。吉尔卡

所以这是结论:添加到您的模块安装程序/激活程序

package master;

import org.openide.modules.ModuleInstall;

/**
 * Manages a module's lifecycle. Remember that an installer is optional and
 * often not needed at all.
 */

public class Installer extends ModuleInstall {

 @Override
 public void close() {
  //your module shutdown
 }

 @Override
 public boolean closing() {

 // this is place for your Dialog() and return:
 //
 //        true if you want to enable close the app
 //        other return false
/*
 if you force shutdown app try LifecycleManager.getDefault().exit();
 System.exit(0) is very dummy, because it does not respect betweenmodule dependencyis

 }  
}

吉尔卡

于 2012-10-14T07:11:33.230 回答
-1

如果windowClosing()密码正确,请从用户和dispose()框架中获取密码。

public class PasswordToClose extends WindowAdapter {

  private JFrame frame;

  public PasswordToClose(JFrame frame) {
    this.frame = frame;
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Password to close");
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    frame.addWindowListener(new PasswordToClose(frame));
    frame.setSize(200, 200);
    frame.setVisible(true);
  }

  @Override
  public void windowClosing(WindowEvent evt) {
    String password = JOptionPane.showInputDialog(frame, "Enter password");
    if ("secret".equals(password)) {
      frame.dispose();
    }
  }
}
于 2012-07-20T16:15:49.790 回答