我正在构建一个NetBeans平台应用程序。当用户点击主窗口的X时,我希望应用程序什么也不做,并显示密码JDialog。如果密码正确,请关闭应用程序,否则请关闭应用程序。我该怎么做呢?我已经创建了一个监听器类,它将显示密码JDialog,但是如何阻止应用程序关闭?与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());
}
});
}
}
答案 0 :(得分: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
}
}
日尔卡
答案 1 :(得分:-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();
}
}
}