Solved

java program with button to run a batch file from windows

Posted on 2004-10-22
695 Views
Last Modified: 2013-11-23
Hello,

Im kinda new to java but not other languages.  I need to write a program in java which has an interface from windows and is ran from a windows icon.

the first thing i want to do is have the program execute a batch file called DTASelect.

Ive written jsp's and was able to run lots of commands through

  Process DTA = Runtime.getRuntime().exec(" ");

normally from the dos prompt to run DTASelct u just type DTASelect

I tried the following:

import java.io.*;
import java.lang.*;
import javax.swing.*;
public class hello
{
  public static void main( String[] args ) {
try{
      Process DTA = Runtime.getRuntime().exec("C:\\DTASelect\\DTASelect");   //location of batch file

      Process p = Runtime.getRuntime().exec("dir");
 
      JFrame frame = new JFrame( "HelloJava" ); //program i started with
      JLabel label = new JLabel("Hello, Java!", JLabel.CENTER );  //same
    frame.getContentPane().add( label ); //same
    frame.setSize( 300, 300 );//same
    frame.setVisible( true ); //same
  }
catch(Exception e) {
      System.out.println("no good");
    }



}}

the program just prints out "no good"

Im just starting out here ... i figure once i can get the java program to run DTASelect adding a button and other properties to cause this shouldnt be too difficult.

on a different note when i run java  programs on ms dos with classes they dont seem to like them

i get the error: "exception in thread 'main' java.lang.NoClassDefFoundError: HelloComponent2 - eventho this program was from a book and should work fine - could compile and all
 
0
Question by:bryanberg
    10 Comments
     
    LVL 13

    Expert Comment

    by:petmagdy
    does the batch file DTASelect has extension like .cmd or .bat if so then change the line from :

         Process DTA = Runtime.getRuntime().exec("C:\\DTASelect\\DTASelect");   //location of batch file

    to:

         Process DTA = Runtime.getRuntime().exec("C:\\DTASelect\\DTASelect.bat");   //location of batch file
    0
     
    LVL 9

    Expert Comment

    by:DrWarezz
    Yeah, petmagdy's advice should solve that.
    Check out http://www.javaalmanac.com/egs/java.lang/Exec.html for more info on using command via Java.

    >"is ran from a windows icon."
    Create a JAR file. Check out: http://java.sun.com/docs/books/tutorial/jar/basics/ for more info on how to do that. :) And just ask if you have any trouble.

    HTH :)
    [r.D]
    0
     

    Author Comment

    by:bryanberg
    hello again

    thanks for the response ... the DTASelect command is now working ...

    except when we used to run it from the dos prompt the output of the program would be displayed on the screen.  now the dos prompt does not display anything - this does not matter since were gonna make a windows icon to run the program, but we do want the output to be displayed on the frame that is created in the code above

    any ideas on obtaining the output from this process would be appreciated,

    thanks ! : >

    bryan
    0
     
    LVL 9

    Expert Comment

    by:DrWarezz
    Oh -- did you find a solution to:
    "i get the error: "exception in thread 'main' java.lang.NoClassDefFoundError: HelloComponent2 - eventho this program was from a book and should work fine - could compile and all"
    ??

    If not, it's most probably because the class isn't in the CLASSPATH variable.
    Before compiling and (most importantly) running your class files, type:

    set classpath=%classpath%;%cd%

    ;-)

    So, the batch file isn't giving output? But you need to retrieve it, right?

    Perhaps try passing all output to a file, like so:

        Process DTA = Runtime.getRuntime().exec("C:\\DTASelect\\DTASelect.bat ^> Filename.txt");   //location of batch file

    Then search at: www.javaalmanac.com for "file" to find how to read from a file, and assign the content to a string, which you can then process :)

    If no luck, then you may need to pass all the output commands in the actualy batch file to a text file. If you decide to do that, give me a copy of the batch file, and I'll add all the appropriate output commands. :D

    gL,
    [r.D]
    0
     

    Author Comment

    by:bryanberg
    hmmm ...

    i found this ...

    http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20306549.html?query=process+java+output&clearTAFilter=true

    and was able to get the dos prompt screen to output the results by using ..

    java.io.InputStream in = DTA.getInputStream();

    int r;
    while ((r=in.read()) != -1) System.out.write(r);

    where DTA is the name of my process

    so im thinking that writing the output to a jframe cant be too much more ...

    starting to mess with jTextAreas

    this stuffs kinda tricky so far ...

    the link above might have what i need but when why tried compiling parts i got errors

    thanks again,

    bryan

    0
     

    Author Comment

    by:bryanberg
    well im on my way ... ive got my program to open up a window and then run the DTASelect when a button is clicked ... its still running from a dos prompt tho ...havent gotten to that part about making a windows icon yet ...

    bryan


    import java.io.*;
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
     import java.awt.event.*;



    public class hello

    {
      public static void main( String[] args ) {
    try{
          //Process DTA = Runtime.getRuntime().exec("C:\\DTASelect\\DTASelect.bat");  
          //final Process DTA = Runtime.getRuntime().exec("java -cp c:\\DTASelect DTASelect");  
          //Process p = Runtime.getRuntime().exec("dir");

    //Process p = Runtime.getRuntime().exec();



           //javax.swing.JTextArea textArea;

          //java.io.InputStream in = DTA.getInputStream();
          //java.io.BufferedReader reader = new java.io.InputStreamReader(in); // wrapping the stream

    //String r;
    //while ((r=reader.readLine()) != null) // the reading is slightly changed
        //textArea.append(r + "\r\n");

          JFrame frame = new JFrame( "HelloJava" );
          JLabel label = new JLabel("Hello, Java!", JLabel.CENTER );
          JButton button = new JButton("DTA");
          button.setSize( 50, 50 );


    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          final JTextArea area = new JTextArea( );
            area.setText("Howdy\n");

     
    button.addActionListener(new ActionListener( ) {
          public void actionPerformed(ActionEvent ae) {
    try{
          final Process DTA = Runtime.getRuntime().exec("java -cp c:\\DTASelect DTASelect");
    java.io.InputStream in = DTA.getInputStream();
    InputStreamReader converter = new InputStreamReader(in);
    BufferedReader reader = new BufferedReader(converter);
    String r;
    while ((r=reader.readLine()) != null) // the reading is slightly changed
    area.append(r + "\r\n");

      }
    catch(Exception e) {
          System.out.println("no good");
        }


    } });




    //java.io.BufferedReader reader = new java.io.InputStreamReader(in); // wrapping the stream


    //int r;
    //while ((r=in.read()) != -1) System.out.write(r);
    //while ((r=in.read()) != -1) area.setText(r);

    //javax.swing.JTextArea textArea;
    //textArea.append("hello");
    Container c = frame.getContentPane( );
        c.add( label,BorderLayout.NORTH);
        c.add( area,BorderLayout.CENTER);
        c.add( button,BorderLayout.SOUTH);      
          frame.setSize( 300, 300 );
        frame.setVisible( true );
      }
    catch(Exception e) {
          System.out.println("no good");
        }

    }}
    0
     

    Author Comment

    by:bryanberg
    Hello again,

    well I seem to be having problems with my jar file

    I was able to create a jar file using Orely's Learning Java 2nd edition

    but then when I added the myManifest.mf file, which looks like this:

    Main-Class: hello

    and then try to run the jar program I get the error:

    "Exception in thread "main" java.lang.NoClassDefFoundError: hello

    i changed the classpath to allow java to lookinto the jar file with:

    set claspath=%classpath%;%cd%;C:\DTASelect\test_run\DTAj.jar

    help ! (ive already tried redoing it)

    0
     

    Author Comment

    by:bryanberg
    well Ive gotten the program to run from the windows icon but not my using the jar method

    instead I created a batch file which ran the java program and then made a shortcut to the batch file to be in the same directory as the main class file.

    but i still want to know how to get that jar program to work - im guessing ive either done something wrong with either the myManifest.mf file or the classpath directory

    after agonizing over it for the last day id really like to figure this out - id imagine itll be helpful in the future

    btw any known problems with using the batch file ?

    what are the benefits to using the jar file ? - im guessing with a jar file the pc doesnt have to have java installed on it ...

    0
     
    LVL 9

    Accepted Solution

    by:
    Hi Bryan,
    Sorry about this large delay, I'm here to help though now... :-)

    >"set claspath=%classpath%;%cd%;C:\DTASelect\test_run\DTAj.jar"
    I hope that was just a typoe will typing into the EE screen.. right? Because you've put: set claspath= ...
    Whereas it SHOULD be:  set classpath= ...

    >"im guessing with a jar file the pc doesnt have to have java installed on it ..."
    Incorrect. To run ANY java program, the machine MUST have JRE (Java Runtime Environment) installed! :-(
    Even for JAR files.
    If you want to be able to run the file without needing JRE installed, you must use a 'Bytecode to Native Code' compiler. Which turns the JAR file into an EXE. However, you must pay for these (well, good ones). The best FREE one can't compile Java programs that use the SWING package (for the GUI)!!!  So, forget about that! :-)

    Anyways, the advantages of a JAR file. Well, it depends what you're using them for, if you're building an applet, they help ALOT, and speed up the download time (for the client).

    But also, if your software uses other files, such as images, then you can compile all of these files, and compress them into ONE! :D
    Meaning that you only need to send your mate ONE file to use it, and only requires a double-click to run it (assuming he has JRE installed). JAR files are very useful.

    >"btw any known problems with using the batch file ?"
    erm... Not really. But it's definitely NOT the best method. I'll try and help you to get the JAR file working, but until then, use this method:
    Create a shortcut, with the following line:

    javaw -cp c:\directory ClassName

    So, let's imagine that you have the following:

       c:\directory\ClassName.class
     
    Then you'd use:

    javaw -cp c:\directory ClassName

    As the shortcut. :-)

    Then you just double-click the shortcut, and off you go. However, if you're using imagery, you really want to just use a JAR file, you'll find out why if you try the above method with images. ;-)

    As for the JAR problem, have you seen here:
    http://java.sun.com/docs/books/tutorial/jar/basics/

    I think creating and using JAR files is explained pretty well there :-)

    Let me know if you have any problems.
    Good luck,
    [r.D]
    0
     
    LVL 9

    Expert Comment

    by:DrWarezz
    8-) Thanks V..
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

     Java Android Coding Bundle

    Whether you're an Apple user or Android addict, learning to code for the Android platform is an extremely valuable, in-demand skill. It all starts with Java, the language behind the apps and games that make Android the top platform it is today.

    Suggested Solutions

    Title # Comments Views Activity
    isEverywhere  challenge 19 38
    either24  challenge 19 58
    pre4 challenge 19 56
    how to extract window origin in spring 2 39
    For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
    The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

    934 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now