java - 使用 Java 启动外部程序?

标签 java external-process audio-player

问题:在一段时间后自动关闭程序。

解决方案:这是我解决问题的方法(在 Ubuntu 上与 Rhythmbox 配合使用):

package rhythmBox;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class closeRhythmBox extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JTextField minutesBox;

public static void main(String[] args) {
    new closeRhythmBox().setVisible(true);
}

public static void execKill(long minutes) throws InterruptedException {
    Thread.sleep(minutes*60*1000);
    try{
    Runtime.getRuntime().exec("pkill rhythmbox");
    System.exit(0);
        }
    catch (IOException ioe) {
          ioe.printStackTrace();
        }
}
public closeRhythmBox(){
    setTitle("Rythmbox Timer");
    setSize(WIDTH, HEIGHT);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container pane = getContentPane();
    pane.setLayout(new FlowLayout());

    JPanel box = new JPanel();
    box.setLayout(new FlowLayout());
    JButton startButton = new JButton("Start");
    startButton.addActionListener(this);
    box.add(startButton);
    box.add(new JLabel("Minutes Until Close"));
    box.add(minutesBox = new JTextField(20));

    pane.add(box);
    pack();

}

public void actionPerformed(ActionEvent e) {
    String textNum = minutesBox.getText();
    long minuteNum = Long.parseLong(textNum);
    if (e.getActionCommand().equals("Start")){
        try {
            execKill(minuteNum);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }
}   

}

最佳答案

您可能无法以这种方式启动 EXE。我认为这是为了使用默认应用程序打开文件,而不是自己运行应用程序 - 要么这样,要么您只是遇到了 Windows 安全问题。

您可以使用 Java.lang.Process 来运行带参数的程序。

关于java - 使用 Java 启动外部程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4989749/

相关文章:

java - java程序的单元测试

python - multiprocessing - 执行外部命令并在继续之前等待

audio - wasapi:检测到没有播放任何内容(设备未在使用中)

python - 如何避免Pygame将女性声音转换为男性

java - 优先队列轮询

java - 无法在android中创建数据库

python - C++:如何检查外部程序是否正在运行?

Java 打开外部程序然后关闭java程序

ios - 按下按钮后如何在屏幕事件的同时播放声音

java - 在ArrayList中,如果子目录的父目录已存在于列表中,如何删除子目录?