Java, run another application in foreground

大兔子大兔子 提交于 2019-12-01 02:09:07

问题


I want run another application from java code.

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("cmd.exe");

Process is launched, but in background. How to make it run in foreground?


回答1:


You should tell cmd.exe that you want it to open in new window:

Process pr = rt.exec("cmd.exe /c start");



回答2:


Process#waitFor() is what you're looking for.




回答3:


Consider using commons-exec when dealing with external processes. In my opinion it is much easier to handle than using the Java Runtime class.

Tutorial : http://commons.apache.org/exec/tutorial.html




回答4:


Run your command from a JDialog and after running it, use toBack().

final JDialog dlg = new javax.swing.JDialog(null, "test", JDialog.ModalityType.DOCUMENT_MODAL);
dlg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JButton button = new JButton("Select Me");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            java.awt.Desktop.getDesktop().open(
                    new java.io.File("/home/user/Downloads/jfreechart-1.0.13-US.pdf"));
            dlg.toBack();
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }
});


来源:https://stackoverflow.com/questions/11983803/java-run-another-application-in-foreground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!