1
votes

Hi I would like to integrate my batch file (stages.bat) into my Java Gui but I do not know how. I have referred to these two websites:

Integrating batch script into Java GUI? and How to integrate batch script multiple selections into JAVA GUI?

However, these answers doesn't help much and there are errors when I run my java codes.

This is my batch code (example):

@echo off
setLocal Enabledelayedexpansion

for %%d in (D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
if exist %%d:\ (
    if exist %%d:\stages.bat (
        %%d:
        )
    )
)

@For /F "tokens=1,2,3 delims=/ " %%A in ('Date /t') do @( 
   Set Day=%%A
   Set Month=%%B
   Set Year=%%C
)

setlocal enableDelayedExpansion
set "baseName=Stage-%Year%%Month%%Day%-"
set "n=0"
:loop
set /a n+=1
if exist "%baseName%%n%.txt" goto :loop
rem type nul > "%baseName%%n%.txt"

SETLOCAL ENABLEDELAYEDEXPANSION 
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
SET sourcedir=%d%
SET "choicebet= 123456789abcdefghijklmnopqrstuvwxyz"
FOR /f "tokens=1*delims=[]" %%a IN (
  'dir /b /a-d "%sourcedir%\*.raw" ^|find /n /v ""'
  ) DO (
 SET $!choicebet:~%%a,1!=%%b
 SET /a choices=%%a+1
)
)
CALL SET choices=%%choicebet:~0,!choices!%%
IF DEFINED $2 (
 cls
 FOR /f "tokens=1*delims==" %%a IN ('set $') DO SET "choicemade=%%a : %%b"&ECHO(!choicemade:~1!
 choice /c %choices:~1% /M "You have MORE than 1 raw files. Please select one."
 REM SET /a choicemade=!errorlevel!-1
 CALL SET choicemade=$%%choicebet:~!errorlevel!,1%%
 ) ELSE (
 SET choicemade=$1
)
FOR /f "tokens=1*delims==" %%a IN ('set %choicemade%') DO SET choicemade=%%b

cls

setlocal enabledelayedexpansion
echo Please select your functions for %sourcedir%%choicemade%
echo.
echo 1. Stage1
echo 2. Stage2
echo 3. Stage3
echo 4. EndStage
echo 5. All
echo.

:getOptions
set /p "op=Type the number of the functions you need for analysis without spacing (e.g. 1,2,3): "

if not defined op ( 
   echo.
    echo Please enter a valid option
    goto getOptions
   )

cls

SET StartTime=%time%


for %%a in (%op%) do if %%a EQU 5 set op=1,2,3,4
for %%i in (%op%) do call :option-%%i 

echo.
echo Analysis Done
echo Start Time (HH:MM:SS.MS): %StartTime%
echo End Time (HH:MM:SS.MS):%time%
echo.

choice /c yn /m "Would you like to continue with the optional functions?"
if %errorlevel% equ 1 (
    SET StartTime2=%time%
    echo Time to start
    echo *** choose ***
    echo Start Time (HH:MM:SS.MS): %StartTime2%
    echo End Time (HH:MM:SS.MS):%time%
    pause
    exit
    )
 if %errorlevel% equ 2 (
    exit
   )

:option-1
echo Action made.
echo Better analysis to be done later.
echo Start %choicemade% soon >> %baseName%%n%.txt

exit /B

:option-2
echo Stage 2 done.
echo Recording %choicemade% soon >> %baseName%%n%.txt

exit /B

:option-3
echo harry potter maybe included in it
echo Ending %choicemade% soon >> %baseName%%n%.txt

exit /B

:option-4
 echo Bye bye
Echo End %choicemade% >> %baseName%%n%.txt
exit /B

Here is my java code (Example):

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;

import java.awt.Window.Type;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.swing.JButton;

 public class GUI extends JFrame {
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static String cmdLine = "";
    private static final String scriptFile = "stages.bat";

    public GUI() {
        setTitle("Raw Files");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 450, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);

        JCheckBox chckbxStage = new JCheckBox("STAGE1");
        chckbxStage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if(!cmdLine.contains("STAGE1"))
                     cmdLine += " STAGE1 ";
            }
        });
        chckbxStage.setBounds(45, 36, 97, 23);
        contentPane.add(chckbxStage);

        JCheckBox chckbxStage_1 = new JCheckBox("STAGE2");
        chckbxStage_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if(!cmdLine.contains("STAGE2"))
                     cmdLine += " STAGE2 ";
            }
        });
        chckbxStage_1.setBounds(45, 89, 97, 23);
        contentPane.add(chckbxStage_1);

        JCheckBox chckbxStage_2 = new JCheckBox("STAGE3");
        chckbxStage_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if(!cmdLine.contains("STAGE3"))
                     cmdLine += " STAGE3 ";
            }
        });
        chckbxStage_2.setBounds(253, 36, 97, 23);
        contentPane.add(chckbxStage_2);

        JCheckBox chckbxEndstage = new JCheckBox("ENDSTAGE");
        chckbxEndstage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if(!cmdLine.contains("ENDSTAGE"))
                     cmdLine += " ENDSTAGE ";
            }
        });
        chckbxEndstage.setBounds(253, 89, 97, 23);
        contentPane.add(chckbxEndstage);

        JCheckBox chckbxA = new JCheckBox("ALL");
        chckbxA.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                 cmdLine = "STAGE1 STAGE2 STAGE3 ENDSTAGE";
            }
        });
        chckbxA.setBounds(45, 142, 97, 23);
        contentPane.add(chckbxA);
        JButton btnOkay = new JButton("Okay");
        btnOkay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                DetectDrive d = new DetectDrive();
                String DetectDrive = d.USBDetect();

                try {

                    String command = "cmd /c start " + DetectDrive+ "stages.bat";
                    Runtime.getRuntime().exec(scriptFile + cmdLine);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnOkay.setBounds(323, 208, 89, 23);
        contentPane.add(btnOkay);

    }
}

I would also like my batch script to run as a subprocess or in the background in my gui. Can anyone help me as I'm still new with Java? thanks

Edit:

I don't understand the errors because there are so many of them:

java.io.IOException: Cannot run program "stage.bat": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at GUI$7.actionPerformed(GUI.java:110) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$400(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) ... 41 more

Anyone can help me understand what these errors mean? I really appreciate any help I can get. Thank you.

1
what is wrong with your code? Do you get any errors?Thusitha Thilina Dayaratne
@ThusithaThilinaDayaratne I have updated my question with the errors I face. Please take a look and thank you for helping.Linify
"The system cannot find the file specified" Check the file location iscorrectThusitha Thilina Dayaratne

1 Answers

0
votes

I see 2 mistakes in your code.

  1. you set the "command", but you're using "scriptfile + cmdLine" to execute.

    String command = "cmd /c start " + DetectDrive+ "stages.bat"; Runtime.getRuntime().exec(scriptFile + cmdLine);

  2. To call a Batch-File you have to do it in the following way. The path of the batch file has to be provided, if it is not located in the current directory

    String command = "cmd /c start " + "c:\temp\hello.bat"; Runtime.getRuntime().exec(command);