0

我正在尝试创建一个类似 java 应用程序的控制台来使用 Runtime.getRuntime.exec() 运行其他 java 程序。进程的输入将从 JTextField 中给出。但进程在给出输入之前正在运行。如何让进程等待来自文本字段的输入?

package org.peditor;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class RunProg extends JFrame implements ActionListener {


private static final long serialVersionUID = 1L;
private String line="",editorString="";
final JTextField intext = new JTextField(25);
JTextArea outtext = new JTextArea(20,40);

public RunProg (String fileName){
    JPanel cp = new JPanel(new BorderLayout());
    intext.addActionListener(this);
    outtext.setEditable(false);
    intext.setEditable(true);
    JScrollPane sp = new JScrollPane(outtext);
    cp.add(sp,BorderLayout.WEST);
    cp.add(intext,BorderLayout.SOUTH);
    this.setContentPane(cp);
    this.setVisible(true);
    this.pack();
    this.setLocationRelativeTo(null);
    this.setTitle("*************OUTPUT CONSOLE***********");
    try
    {
        Runtime r = Runtime.getRuntime();
        Process p = null;
        //Stripping the file extension
        fileName = fileName.substring(0, fileName.lastIndexOf("."));            
        p = r.exec("java "+fileName);
        BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        OutputStream childin = p.getOutputStream();
        BufferedWriter childWriter = new BufferedWriter(new OutputStreamWriter(childin));
        childWriter.write(getInput());
        childWriter.newLine();
        childWriter.flush();
        childin.close();

        while ((line = inputStream.readLine())!=null) 
        {
            editorString = editorString+line+"\n";
            outtext.append(editorString);
        }
        while ((line = errStream.readLine())!=null)
        {
            editorString = editorString+line+"\n";
            outtext.append("ERROR"+"\n"+editorString);
        }
        p.waitFor();
        inputStream.close();
        errStream.close();
    }
    catch(Exception e1)
    {
        outtext.setText("Error running the program  "+e1.getMessage());
    }

}
public void actionPerformed(ActionEvent e) {
    getInput();

}
private String getInput() {
    String s = intext.getText();
    intext.setText("");
    outtext.append(s+"\n");
    return s;
}

}

4

1 回答 1

0

您正在构造函数中调用 exec 方法。显然这是行不通的。您还有一个完全不执行任何操作的随机 actionPerformed。从您的构造函数中删除所有运行时内容,添加一个 JButton,向该 JButton 添加一个 actionListener,并在他们单击该按钮时执行运行时代码。

于 2013-09-22T17:42:57.430 回答