Question About Java Threads and Blocking

I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
// Test ProcessBuilder
public class CommandProcessor {
public static void Run(String[] cmd) throws Exception {
System.out.println("inside CommandProcessor.Run function...");
Process p = new ProcessBuilder(cmd).start();
StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
s1.start();
s2.start();
//p.waitFor();
System.out.println("Process Returned");
Here's the "StreamGobbler" class:
import java.lang.*;
import java.io.*;
// Attempt to make the output of the process go to the message window
// as it is produced rather that waiting for the process to finish
public class StreamGobbler implements Runnable {
String name;
InputStream is;
Thread thread;
public StreamGobbler (String name, InputStream is){
this.name = name;
this.is = is;
public void start(){
thread = new Thread (this);
thread.start();
public void run(){
try{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while (true){
String s = br.readLine();
if (s == null) break;
System.out.println(s);
//messageWindow.writeToMessageArea("[" + name + "]" + s);
is.close();
catch(Exception ex){
System.out.println("Problem reading stream" + name + "...:" + ex);
ex.printStackTrace();
The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
while (s1.thread.isAlive() || s2.thread.isAlive())
// We really don't do anything here
I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
Thank you in advance for your help!

You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

Similar Messages

  • Questions about Java Servlets and JSP

    Hi,
    I'm a confident Java Programmer (and really enjoy using this language) but am very new to Java servlets and Java Server Pages.
    I have previously worked with Perl on my web projects (simple 'league' style voting pages). I read in my 'Core Java' book that I should no longer use perl or even cgi.
    I need to know more about Java servlets and Java Server Pages so I can make the switch to a 'real' programming language.
    I have a few questions:
    How should I start to learn JS and JSP?
    How applicable will the java knowlegdge I have already be?
    Are JSP common on the world wide web?
    What tools do I need to start? (I currently develop in JBuilder and have Java 1.4.1 Standard Edition)
    Is it likey my web host (and others) will support JSP?
    Thank-you very much for helping a novice get started,
    Regards,
    Paul

    Hi, Steve ...has to be frustrating! But do not despair.
    Let's suppose the servlet it's named MyServlet on package org.servlets
    WEB-INF should look:
    WEB-INF
    classes
    org
    servlets
    MyServlet.class
    web.xml
    web.xml file should have this two declarations:
    <web-app>
      <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.servlets.MyServlet</servlet-class>
      </servlet>
      <!-- other servlets -->
      <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
      </servlet-mapping>
      <!-- other servlets mappings -->
    </web-app>Now, once the container starts (Tomcat?), you should be able to see that servlet in:
    http://localhost:8080/[my-context/]MyServletAnd what my-context is? The web application context. This string should be empty if your're deploying to the root context, otherwise should the context name. In Tomcat, deploying to root context defaults to using webapps/ROOT.
    Sorry for my English, but I felt the need to answer your request. I hope it helps despite my writing.

  • Question about java thread implementation

    Hi All,
    I am comparing the performance of the Dining philosopher's problem
    implemented in Java, Ada, C/Pthread, and the experimental language I
    have been working on.
    The algorithm is very simple: let a butler to restrict entry to the
    eating table, so that deadlock is prevented.
    It turns out that the java code is the winner and it is 2 times faster than C!
    The comparison result really surprised me, and raised a big
    question mark : why java runs so fast? I did not use high-level synchronization
    constructs like Semaphores, atomic variables, etc.
    I vaguely recall that Java thread is actually implemented by the underlying
    system thread library(so on linux, the default would be NPTL, on windows NT threads,
    and on Mac OSX it would be Cthread?). Can no longer remember where I read that.
    Does anyone here have some notions about the Java thread
    implementations(where is this formally explained)? or Does anyone know where
    I can possibly find relevant literature or the answer?
    thanks a lot.
    cheers,
    Tony

    Peter__Lawrey wrote:
    google has lots of information on java threaded.
    One thing java does is support biased locking. i.e. the thread which last locked an object can lock that object again faster.
    This may explain the difference. [http://www.google.co.uk/search?q=java+usebiasedlocking]
    Note: you can turn this option off and other locking options to see if a feature is giving you the performance advantage.
    Personally I have found that real world multi-threaded applications are easier to write in Java, esp. when you have a team of developers. For this reason, alot of C/C++ libraries are single threaded, even when there would be a performance advantage in being multi-threaded (because its just too hard in reality to make it thread safe and faster because of it)I didn't know that, very interesting :-)

  • Question about using threads and synchronizing objects

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming connections, then I spawn off a new thread which implements Runnable, and then call the run method. But the loop would not iterate, it would just sit inside the run method (which has rather long loop in it). I changed the class to extend Thread and called the start() method, rather than run(), and everything worked out fine.
    Anyone know why this is?
    QUESTION 2
    So I am building a client server chat application where a user can be in multiple chat rooms. I have this personObject which has output/input streams. In the personObject, I create writeObject/ readObject method, which simply does as it implies.
    I figured that I should make these methods synchronized, to ensure things run smoothly. however, when I made a call to readObject, which sat there and waited, and then made a call to writeObject, I would not enter the writeObject method. I took out the synchronized on the writeObject, and everything worked out fine.
    I was under the assumption that synchronizing a method only synchronized on that method, not on the whole class. How come then was I not able to enter the writeObject method?
    The more I think about it, I don't think I need to have these methods synchronized, but I thought it wouldn't hurt.
    Thanks for the help.

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming
    connections, then I spawn off a new thread which
    implements Runnable, and then call the run method.
    But the loop would not iterate, it would just sit
    inside the run method (which has rather long loop in
    it). I changed the class to extend Thread and called
    the start() method, rather than run(), and everything
    worked out fine.
    Anyone know why this is?
    You should still implement Runnable, rather than extending Thread. Like this: Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start(); run() is just another method. Nothing special about it as far as multithreading or anything else goes.
    start() is the method that actually spawns a new thread of execution.
    I was under the assumption that synchronizing a
    method only synchronized on that method, not on the
    whole class. How come then was I not able to enter
    the writeObject method?When you synchronize, you obtain a lock. As long as you hold that lock--until you exit the sync block or call wait()--no other thread can enter that block or any other block that obtains the same lock.
    Two synchronized methods on the same object rely on obtaining the same lock--there's one lock for each object.

  • Question about Java,XSLT and XML

    I am new to Java and XML. I'm not quite clear the relationship between Java,XSLT and XML.
    To exercise, I am going to write a Java program that makes embedded calls to an XSLT processor(XALAN), to produce results for several constrained transformations from a given XML document(x.xml) such as:
    1.Transform the x.xml (which satisfies d1.dtd) in such a way that it now conforms to the DTD d2.dtd. Output the resulting xx.xml document.
    2.query some information from the x.xml and then form an Html output.
    3.summary some information, do some statistics from the x.xml and then form an Html output.
    I don't konw which java classes and XSLT functions might be used.(Actually I don't know how/where to start).
    Can anyone give me some clue ?
    thanks a lot!

    You must provide XSLT stylesheeds to specify transformations (1), (2),
    and (3); let's call those stylesheets task1.xsl and so on.
    The following code will transform x.xml into xx.xml according to task1.xsl. It gives you an idea which packages and classes to use, but it doesn't teach you proper Java programming technics :)
    import java.io.File;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    public class Test
        public static void main(String[] args) throws Exception
            TransformerFactory factory = TransformerFactory.newInstance();
            Source config = new StreamSource(new File("task1.xsl"));
            Transformer transformer = factory.newTransformer(config);
            Source source = new StreamSource(new File("x.xml"));
            Result result = new StreamResult(new File("xx.xml"));
            transformer.transform(source, result);
    }To read about XSLT, see:
    http://www.w3.org/TR/xslt
    there is a tutorial on using XSLT with Java:
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/xslt/index.html.

  • Question about java threads programming

    Hi
    I have to develop a program where I need to access data from database, but I need to it using multithreading, currently I go sequentially to each database to access data which is slow
    I have a Vector called systemnames, this one has list of all the systems I need to access.
    Here is my current code, some thing like this
    Vector masterVector = new Vector();
    GetData data = new GetData();
    For(int i =0; i < systemnames.size(); i++)
    masterVector.add(data.getData((String)systemnames.get(i));
    public class GetData
    private Vector getData(String ipaddress)
    //process SQL here
    return data;
    how do i convert this to multithread application, so there will be one thread running for each system in vector, this is speed up the process of extracting data and displaying it
    has any one done this kind of program, what are the precautions i need to take care of
    Ashish

    http://www.google.com/search?q=java+threads+tutorial&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    http://java.sun.com/docs/books/tutorial/essential/threads/
    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html
    http://www.cs.clemson.edu/~cs428/resources/java/tutorial/JTThreads.html
    http://www-106.ibm.com/developerworks/edu/j-dw-javathread-i.html
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Question about Java RMI and Eclipse

    I would like to create an application with which I can easily connect to a JAVA program, installed on a web server, through JAVA RMI. I have already created a ClientRMI.java and a ServerRMI.java and compiled them. The stubs also have been created properly.
    When I run the application outside the Eclipse editor, everything works just fine! However, when I want to integrate the files into a bigger project in Eclipse... and starts running it, he tells me he can't find the stub class or something like that. I need to place this one in the classpath but I don't know how to do that in Eclipse? Could anyone help me with this problem?
    Thanks!
    This is the fault message I get:
    no security manager: RMI class loader disabled)
    D-me

    Do you have an idea of what the answer to our
    question could be?I don't have much idea about the question myself. I was groping in the dark. :-)
    Anyway, the project classpath settings and the external jars (or dependent projects) are a few things which could be experimented with. I'm afraid I couldn't be much help without having a look at what you are trying to do. :-(
    Regards,
    x

  • Question about Java applets being blocked.

    -I have succeeded in getting the 32 bit Java 8 applet plugin for Windows 7 Firefox v34 running.
    However, I have a situation where the applet loader itself has started blocking my applets.
    I have allowed the applet through in an unwiedly fashion.
    I can't find a way to generally lower the java plugin security applet blocker to allow
    unsigned applets. The only option I have is adding
    that webpage file reference to the exceptions list, closing the web browser
    and restarting it.
    The Java control panel Security Level radio buttons
    only exist for Very High and High; I do believe I want lower.
    However there isn't an auto selection for one.
    -How can I just click one button within Firefox to allow
    an applet through, and begin to run, if I want?

    -I have succeeded in getting the 32 bit Java 8 applet plugin for Windows 7 Firefox v34 running.
    However, I have a situation where the applet loader itself has started blocking my applets.
    I have allowed the applet through in an unwiedly fashion.
    I can't find a way to generally lower the java plugin security applet blocker to allow
    unsigned applets. The only option I have is adding
    that webpage file reference to the exceptions list, closing the web browser
    and restarting it.
    The Java control panel Security Level radio buttons
    only exist for Very High and High; I do believe I want lower.
    However there isn't an auto selection for one.
    -How can I just click one button within Firefox to allow
    an applet through, and begin to run, if I want?

  • Basic question about Java, UNIX and OAS

    Hi,
    Can I create an appication that contains GUI components like testbox and textfields etc...and then load/import it into OAS?
    Can I again, create such an GUI application and then load it UNIX platform and run it?
    The reason I asked because I did create an application which has a frame, a panel and couples of buttons, text fields then ftp it to Unix Solaris, when I ran it with jre command, I got the following message:
    java.lang.NoClassDefFoundError: Javax/Swing/UIManager at cms.CMSApp.main(compiled code) Exception in thread main
    Please anyone help me to clarify this, I don;t if we can do such things but I did not do it the right way? or we cannot do it at all. Thanks for your help
    Minh

    I'm not sure I understand where OAS fits in here.. Is this an applet?
    In any case, it sounds like the JDK version you are using is 1.1.x, and swingall.jar is not in the classpath.
    If it's an applet, then you need to edit the HTML file and add in swingall.jar.
    If it's an application, you need to edit the CLASSPATH environment variable and append the full path to swingall.jar
    (note: in Java2 (JDK 1.2, 1.3) swingall.jar is no longer seperate, it is part of the runtime classes of java, so you don't have to add anything to the classpath)
    Take Care,
    Rob
    null

  • Question about java objects and handles?

    Let me see if I can explain what I have. Inside my originating Java code, I create an object, let's call it object A, from a class I that I DON'T have the source for. It's not my class. Object A in turn creates an object, let's call it Object B, from a class I don't have the source for. Then Object A creates another object, let's call it Object C, that I DO have the source for, and passes it the reference to Object B that it created. My question is this: In my originating Java code, how do I get a reference to Object B? Or, how can I get the reference to Object C, which would allow me to get the reference to Object B?
    Hope everyone understands that?

    Thanks for the reply. Perhaps I should have mentioned that Object A does not have a method to return a referenece to Objects B and C. That's my problem. Was just wondering if there is some other way to obtain those refereneces. The reason I mentioned that I don't have the source code for Object A is because if I did, I could obviously write a method that would return me the references.
    I'm not new to Java, nor am I an expert either. I'm pretty well up-to-speed on object oriented design though.
    I'll provide more specifics on my problem just in case there is a solution to my problem. My code (class) is attempting to establish a connection with a mainframe computer through a web server portal using terminal emulation software provided by a 3rd party vendor. They provide an SDK that contains all the java classes necessary to establsih the connection. To establish the connection, you are required to build a java Properties object that contains all the parameters for the connection (host id, etc.) and pass that properties object to the constructor for the "Object A" class. That object actually establishes the session object using the parameters object you pass it. The session gets displayed in a standalone Applet ("Object A" class extends Applet). You can click on the applet, sign in to the system, and do whatever just fine using your keyboard. However, I wish to send commands to the session from my originating java code. The session object has a method to send commands to the session, but to do that, I need a handle to the session object that was created. I don't have that, and it appears they don't provide a method to get that. Looks like the vendor's intent was just for the user to interface with the session/Applet via the keyboard.

  • Short question about networking, Threads and  web services..

    Lets say I got 2 classes, Midlet A and Thread B.
    I created Thread B because web services (jsr-172) uses networking and It has to be done in a separate thread other then the Midlet A.
    So, in Thread B, I have the run(), where I do all my stuff, and some getSomething() methods.
    I need to have run() complete before calling getSomething(), so I used something like this in Midlet A:
    while(true){
        if(b.isAlive())
            getSomething();
    }Problem is, Thread B only runs to completion when I don't call b.isAlive(). (I know from System.out.println I placed in it) When I do use any methods like wait() or join() or isAlive(), Thread B stops at the web service call.
    I really don't understand what's the problem. I've tried various ways to only call getSomething() when the thread finishes running, but all of them made my WTK emulator hang at the part where it asks for permission to access the network.
    If I don't use getSomething(), which is the purpose of starting the thread in the first place, it runs fine in the emulator and doesn't hang anywhere. Oh the irony.

    Bump!
    Anyone got even half a clue what's wrong? =O
    Hmm. I think that having the midlet wait for the thread causes the midlet to hang because the thread will then wait for the midlet for permission to access the network, but the midlet is waiting for the thread to finish it's code. Damn.
    Message was edited by:
    lonereaction

  • Question about java reflection and "int" type

    hi, using reflections I should invoke a Method (meth3) that have as parameter an INT type (not integer). I've tryed with this code:
                        int num = 3;
                        Class[] vettClax = {int.class};
                        Object[] vettParam = {num};
                        Method meth3 = temp.getMethod("meth3", vettClax);
                        meth.invoke(o, vettParam);My problem is that the int value is catched as an Integer value and reflection doesn't found a method that accept an INTEGER as parameter, who can help me?

    Works fine when I try it.
    public class t
        public static void main(String args[])
         throws Exception
         Class temp = t.class;
         t o = new t();
         int num = 3;
         Class[] vettClax = {int.class};
         Object[] vettParam = {num};
         Method meth = temp.getMethod("meth3", vettClax);
         meth.invoke(o, vettParam);
        public void meth3(int n)
         System.out.println("hello " + n);
    }Is your meth3() public?

  • Question about Java's HttpServer: Threading? Backlog?

    Hello,
    I have two questions about Java's HttpServer (com.sun.net.httpserver). From the JavaDoc:
    >
    Management of threads can be done external to this object by providing a Executor object. If none is provided a default implementation is used.
    >
    How can I get information about the default implementation in 1.6.0_13? Do you know the behavior? From my observations, the default implementation uses no Threads, meaning every request is handled in the same Thread, this results in handling the requests to the HttpServer one after another.
    Is this right?
    The second question is about this, also from the JavaDoc:
    >
    When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. [...]
    >
    When setting the backlog to -1, it uses the systems default backlog. How can I determine the systems default backlog? Can some lines of Java code reveal it (there is no getBeacklog() method)? Or is it up to the Operating System (we use Redhat Linux)?
    Thanks a lot for your help!
    Regards,
    Timo

    How can I determine the systems default backlog?You can't. There is no API for that even at the C level.
    Can some lines of Java code reveal itNo.
    Or is it up to the Operating System (we use Redhat Linux)?Yes. Linux provides a large default. It seems to be at least 50 on most platforms. This is not something you should be worrying about.

  • Three questions about Java and Ftp

    Hello, i've the following questions about Java and Ftp:
    1- .netrc file is in $HOME directory but i can't access to this directory from java code. The following line producesan Exception (directory doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");
    2- .netrc file must have the following permissions: -rw- --- --- but when i create the .netrc file the following permissions are on default: -rw- r-- r--, how can i change this permissions? (In java code, i can't use chmod.....)
    3- Are there any way to pass parameters to a .netrc file? If i get to do this i needn't change the permissions because i can't modify or create/destroy this file.
    Thanks in advanced!!!
    Kike

    1- .netrc file is in $HOME directory but i can't
    access to this directory from java code. The
    following line producesan Exception (directory
    doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");$HOME would have to be replaced by a shell, I don't
    think you can use it as part of a legal path.
    Instead, use System.getProperty("user.home");
    Ok, thanks
    2- .netrc file must have the followingpermissions:
    -rw- --- --- but when i create the .netrc file the
    following permissions are on default: -rw- r--r--,
    how can i change this permissions? (In java code,i
    can't use chmod.....)Yes, you can: Runtime.exec("chmod ...");
    I need to use estrictly the .netrc with -rw- --- --- permissions
    Yes, i can use Runtime.exec ("chmod ..."); but i don't like very much this solution because is a slow solution, am i right?
    3- Are there any way to pass parameters to a.netrc
    file? If i get to do this i needn't change the
    permissions because i can't modify orcreate/destroy
    this file.I don't think so. Why do you need the .netrc file in
    Java at all? Writing a GUI frontend?I want to use automatic ftp in a java program and FTP server, the files and path are not always the same, so i can:
    - modify .netrc (for me is the complex option)
    - destroy and create a new .netrc (is easier but i have permissions problem)
    - use .netrc with parameters but i haven't found any help about it
    Thanks for your prompt reply!!!!
    Kike

  • Questions about ActiveX Bridge and SWT

    Hi !
    I found few weeks ago the www.reallyusefulcomputing.com site answering my question about Java & Macro of MSWord. Now I've found two steps that I am not able to overcome.
    First, when I build a simple application and I have internal libraries to use, am I compelled to place the jars in the lib/ext directory of the Java Runtime Directory? I have many difficulties in placing a convenient class-path in the manifest file. Why does the application ignore the manifest string?
    The second problem (and the biggest one) is that I am trying to build an SWT java-bean-application but I have problems during runtime. Is it possible to use this technology for my software or am I compelled to use AWT and SWING?
    I really hope you can help me.
    Thank you in advance.

    hi,
    I have to catch events from excel sheet in my java code..events like some change in value or a click of some user defined button etc.I have written th follwoing code but it does not gives me any event.It simply opens the specified file in the excel in a seperate window.but when i click on the sheet or change some value no event is captured by my code....can ne one pls tell me how to go about it....
    public class EventTry2 {
         private Shell shell;
         private static OleAutomation automation;
         static OleControlSite controlSite;
         protected static final int Activate = 0x00010130;
         protected static final int BeforeDoubleClick = 0x00010601;
         protected static final int BeforRightClick = 0x000105fe;
         protected static final int Calculate = 0x00010117;
         protected static final int Change = 0x00010609;
         protected static final int Deactivate = 0x000105fa;
         protected static final int FollowHyperlink = 0x000105be;
         protected static final int SelectionChange = 0x00010607;
         public void makeVisible()
              Variant[] arguments = new Variant[1];
              arguments[0]=new Variant("true");
              //Visible---true
              automation.setProperty(558,arguments);
              //EnableEvent--true
              boolean b =automation.setProperty(1212,arguments);
            System.out.println(b);
             public Shell open(Display display){
             this.shell=new Shell(display);
              this.shell.setLayout(new FillLayout());
              Menu bar = new Menu(this.shell,SWT.BAR);
              this.shell.setMenuBar(bar);
              OleFrame frame = new OleFrame(shell,SWT.NONE);
            File file= new File("C:\\Book1.xls");
              try{
              controlSite =  new OleControlSite(frame, SWT.NONE, "Excel.Application");
              this.shell.layout();
              boolean a2=true;
              a2=(controlSite.doVerb(OLE.OLEIVERB_SHOW|OLE.OLEIVERB_OPEN|OLE.OLEIVERB_UIACTIVATE|OLE.OLEIVERB_HIDE|OLE.OLEIVERB_PROPERTIES|OLE.OLEIVERB_INPLACEACTIVATE)== OLE.S_OK);
              System.out.println("Activated::\t"+a2);
            }catch(SWTException ex)
                 System.out.println(ex.getMessage());
                 return null;
              automation = new OleAutomation(controlSite);
              //make the application visible
              makeVisible();
              System.out.println("Going to create Event listener");
              OleListener eventListener=new OleListener(){
                   public void handleEvent(OleEvent event){
                        System.out.println("EVENT TYPE==\t"+event.type);
                   switch(event.type){
                   case Activate:{
                        System.out.println("Activate Event");
                   case BeforeDoubleClick:{
                        System.out.println("BeforeDoubleClick Event");
                   case BeforRightClick:{
                        System.out.println("BeforeRightClick Event");
                   case Calculate:{
                        System.out.println("Calculate Event");
                   case Change:{
                        System.out.println("Change Event");
                   case Deactivate:{
                        System.out.println("DeActivate Event");
                   case FollowHyperlink:{
                        System.out.println("Activate Event");
                   case SelectionChange:{
                        System.out.println("Activate Event");
                        Variant[] arguments = event.arguments;
                        for(int i=0;i<arguments.length;i++)
                             System.out.println("@@");
                             arguments.dispose();
              System.out.println("outside");
              OleAutomation sheetAutomation=this.openFile("C:\\Book1.xls");
              controlSite.addEventListener(sheetAutomation,Activate,eventListener);
              controlSite.addEventListener(sheetAutomation,BeforeDoubleClick,eventListener);
              controlSite.addEventListener(sheetAutomation,BeforRightClick,eventListener);
              controlSite.addEventListener(sheetAutomation,Calculate,eventListener);
              controlSite.addEventListener(sheetAutomation,Change,eventListener);
              controlSite.addEventListener(sheetAutomation,Deactivate,eventListener);
              controlSite.addEventListener(sheetAutomation,FollowHyperlink,eventListener);
              controlSite.addEventListener(sheetAutomation,SelectionChange,eventListener);
              shell.open();
              return shell;
         public OleAutomation openFile(String fileName)
              Variant workbooks = automation.getProperty(0x0000023c);//get User Defined Workbooks
              Variant[] arguments = new Variant[1];
              arguments[0]= new Variant(fileName);
              System.out.println("workbooks::\t"+workbooks);
              IDispatch p1=workbooks.getDispatch();
              int[] rgdispid = workbooks.getAutomation().getIDsOfNames(new String[]{"Open"});
              int dispIdMember = rgdispid[0];
              Variant workbook = workbooks.getAutomation().invoke( dispIdMember, arguments );
              System.out.println("Opened the Work Book");
              try {
                   Thread.sleep(500);
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              int id = workbook.getAutomation().getIDsOfNames(new String[]{"ActiveSheet"})[0];
              System.out.println(id);
              Variant sheet = workbook.getAutomation().getProperty( id );
              OleAutomation sheetAutomation=sheet.getAutomation();
              return(sheetAutomation);
         * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Display display=new Display();
              Shell shell=(new EventTry2()).open(display);
              while(!shell.isDisposed()){
                   if(!display.readAndDispatch()){
                        display.sleep();
              controlSite.dispose();
              display.dispose();
              System.out.println("-----------------THE END-----------------------------");

Maybe you are looking for