开发者

Modal-like dialog in conjunction with Runtime.exec in java

I'm running an external program from within Java and waiting for it to finish:

Process p = Runtime.getRuntime().exec("notepad");
p.waitFor();

This is called from a GUI application and I would like to prohibit the user to do anything in the GUI while the external program is running. There is already such a mechanism which开发者_JS百科 is the modality of a JFrame. So I thought that I could create a dialog window, which also very conviently could state that the user has to exit the external program in order to continue, that would pop-up and block access to the GUI:

Process p = Runtime.getRuntime().exec("notepad");

JOptionPane pane = JOptionPane("close the app", JOptionPane.NO_OPTION, JOptionPane.INFORMATION_MESSAGE, [], "Force Exit", "Force Exit");
JDialog dialog = JDialog(frame, "External app", true);
dialog.setContentPane(pane);
dialog.pack();
dialog.setVisible(true);

p.waitFor();
dialog.setVisible(false);

This approach unfortunately waits at

  1. dialog.setVisible(true)
  2. p.waitFor()

setting dialog.setModal(false) before dialog.setVisible(true) the program only waits for the external program to terminate and then it closes the dialog, but this also allows the user to interact with the GUI.

Any ideas?


Found a way, which is not that bad I guess:

// Parent JFrame somewhere
JFrame parent = ....

// Create the dialog content
String str = "Close the external program when done";
Icon i = UIManager.getIcon('OptionPane.informationIcon');
JLabel lb = JLabel(str, i, JLabel.LEFT);
JPanel panel = JPanel();
panel.add(lb);

// Create the dialog window
JDialog dialog = JDialog(parent, "External app", false);  // N.B: NOT modal
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setContentPane(panel); 
dialog.pack(); 
dialog.setVisible(true);  
parent.setEnabled(false);

// start external app
Process p = Runtime.getRuntime().exec("notepad");
p.waitFor();     // wait for it to close

dialog.setVisible(false); 
parent.setEnabled(true);
parent.requestFocus();

This will disable the use of the parent JFrame as long as the external program is still running, and behave much like a modal dialog.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜