我一直在研究Java,我想制作一个应用程序来打开Mac上的终端等其他应用程序。
我多次失败让它开始工作,我现在有点困惑。
这是我的代码
package pac;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
public class VnET extends JFrame {
public VnET() {
JFrame frame = new JFrame("Frame");
//Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create components and put them in the frame.
frame.setTitle("VnET");
// Size the frame.
frame.setSize(500, 250);;
// Show it.
frame.setVisible(true);
//centers window
frame.setLocationRelativeTo(null);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new VnET();
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("Terminal");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing terminal");
}
System.out.println("Terminal returned"+ p.exitValue());
}
});
}
}
这是控制台日志
Error executing terminal
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at pac.VnET$1.run(VnET.java:43)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
答案 0 :(得分:0)
这不是在Mac上打开终端的正确方法。
p = r.exec("Terminal");
在Mac上,如果您想通过命令行打开应用程序(顺便提一下终端!),您可以使用此命令:
open -a Safari
因此,在Java程序中,使用以下代码行:
p = r.exec("open -a Terminal");
open -a
命令告诉Runtime打开名为“Terminal”的“App”。
有关open命令的更多信息,请参阅this page。
希望这有帮助!