Search code examples
javaswingfile-iojbuttonprocessbuilder

Run command line code on button click


I'm working on a Java program and I want to execute some command line code when the user clicks a button. I have to code to execute my command line code and the button code but I don't now how to combine both: My button code looks like the following:

    private JButton setup;
public ProgramGUI(){
    UsedHandler handler = new UsedHandler();
    setup.addActionListener(handler);

}
private class UsedHandler implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent event) {
        if(event.getSource()==setup)
            JOptionPane.showMessageDialog(null, "Everything fine!");
    }
}

And that's my command line code:

            try {
            Runtime rt = Runtime.getRuntime();
            //Process pr = rt.exec("cmd /c dir");
            Process pr = rt.exec("c:\\helloworld.exe");

            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line=null;

            while((line=input.readLine()) != null) {
                System.out.println(line);
            }

            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);

        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

Thanks!


Solution

  • put your exec code in a method and call it from inside the action performed from your button

    public void yourProcess() {
    try {
            Runtime rt = Runtime.getRuntime();
            //Process pr = rt.exec("cmd /c dir");
            Process pr = rt.exec("c:\\helloworld.exe");
    
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    
            String line=null;
    
            while((line=input.readLine()) != null) {
                System.out.println(line);
            }
    
            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);
    
        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
    

    and then use the method

     @Override
    public void actionPerformed(ActionEvent event) {
        if(event.getSource()==setup){
            yourProcess();
            JOptionPane.showMessageDialog(null, "Everything fine!");
        }
    }