1

我正在从 Java 中运行一个外部程序并等待它完成:

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

这是从 GUI 应用程序调用的,我想禁止用户在外部程序运行时在 GUI 中执行任何操作。已经有这样一种机制,它是JFrame模态。所以我想我可以创建一个对话框窗口,它也可以非常方便地说明用户必须退出外部程序才能继续,这会弹出并阻止对 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);

不幸的是,这种方法等待

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

dialog.setModal(false)程序之前的设置dialog.setVisible(true)只等待外部程序终止然后关闭对话框,但这也允许用户与 GUI 交互。

有任何想法吗?

4

1 回答 1

0

找到了一种方法,我猜这还不错:

// 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();

只要外部程序仍在运行,这将禁用父 JFrame 的使用,并且其行为很像模式对话框。

于 2011-03-23T08:56:01.270 回答