Thread in JTree GUI

I have a GUI with a JTree. Each time I select a node, the valueChanged method is called and a new thread is being started. Now, for various reasons, I only want to have ONE single thread, that is, i don't want Java to start a new thread each time i select a node/leaf (single-threaded application). Any suggestions?

I don't know what that's all about. However if you're updating a Swing GUI from any thread except the Swing thread itself, you should always call EventQueue.invokeLater() or invokeAndWait() to do the updating. You might find this tutorial helpful:
http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

Similar Messages

  • How to post messages between two threads other than GUI main thread?

    Does anyone have examples of post messages between two threads (other than GUI main thread)?  Would you please post the link?
    Thank you,

    Hello, you can call PostDeferredCallToThread passing the your data in callbackData parameter.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How to append msg from second thread to main GUI thread?

    I am facing a problem which I cannot seem to solve.
    It involves Swing and threads. I have a main GUI running on swing. And it retrieves database information and displays it. On the same GUI I have a JTextArea box which I need another thread to update as and when that second thread recieves message via a multicast socket.
    I managed to create a runnable class of the second thread and successfully ran the second thread with the main thread in tandem. However when I use
    display.append(msgreceived);
    I get a nullPointerException. It works fine when i use System.out.println(msgreceived);.
    What should I have done instead?

    Here are part of the codes for my admin module.
    public class Admin extends JFrame implements ActionListener {
    //declares all the global variables
    private JTextArea display;
    public Admin() {
    super("BX Online - Admin Module");
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    AdminGUI();
    AdminGUI() {
    contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel newsbox = new JPanel();
    display = new JTextArea(2, 40);
    display.setEditable(false);
    newsbox.add(display);
    contentPane.add(newsbox);
    contentPane.add(tabpaneO);
    setBounds(70, 50, 300, 500);
    pack();
    setVisible(true);
    // all the methods activated by buttons goes here
    static public void main(String[] argv) {
    Admin a = new Admin();
    News b = new News("test");
    The following are part of the codes for my runnable class.
    public class News implements Runnable {
    protected boolean again = true;
    private String name, recieve; //the global variables
    private Thread t;
    public JTextArea display;
    public BXnews(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New Thread: " + t); //visual check to make sure thread is started.
    t.start();
    private void msg() {
    String recieve = ("testing");
    System.out.println(recieve);
    display.append(recieve);
    public void run() {
    while (again) //creates a loop so thread does not close
    {msg();}
    Well thats abt it. I'm not sure if you can compile this but basically the part I left out was the setup link for the News class which I don't see the need to add as what I primarily intend is for the message testing in News class to appear in Admin class thread in JTextArea "display".

  • Swing/Threads, changing the GUI

    Hey all, I have a question related to the java swing class, and manipulating a GUI which is something that I have never done before. Basically I have a threaded Listener class which returns a status boolean. Related to that status, I have a Jlabel which is supposed to display green if the status is true, and red if the status is false, however it is not working correctly. Below is my code, and I would appreciate some help if anyone has a fix, or better way to do this... Thanks in advance
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener(//...) {
         public void run()
              // does stuff here that sets the isGood var
         public bool getIsGood()
              return this.isGood;
    //GUI
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
              this.listener = listener;
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Window");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    status = new JLabel("Listener... ");
    status.setOpaque(true);
    status.setBackground(Color.RED);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    frame.setSize(new Dimension(204, 115));
    frame.setContentPane(status);
    listener.start();
    while(true){
         boolean isGood = listener.getIsGood();
    if(isGood){
    status.setBackground(Color.GREEN);
    else{
    status.setBackground(Color.RED);
         try{
              Thread.sleep(1000);
         }catch(Exception E){
              E.printStackTrace();
    I purposely left out some of the code because I wanted to make it simpler to follow. Essentially this is what is going on, and hopefully someone can point out why its not working and how to fix it. Thank you for reading this.

    thanks for the advice Petes, I was looking for the code tag before but didnt see it. I have created an SSCCE, and I apologize for not making it earlier. Here is the code. The threads seem to be getting stuck, and the label doesnt alternate between red and green as it should. Let me know if you need anything else:
    package simplified;
    public class Main{
         public static void main(String[] args) {
              Listener theListener = new Listener();
              theListener.start();
              Visualizer theView = new Visualizer(theListener);
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener() {
         public void run(){
              if(this.isGood == true){
                   this.isGood = false;
              else{
                   this.isGood = true;
              try{
                   this.sleep(1000);
              }catch(Exception e){
                   e.printStackTrace();
         public boolean getIsGood(){
              return this.isGood;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Dimension;
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
         this.listener = listener;
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
              //Create and set up the window.
              frame = new JFrame("Window");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              status = new JLabel("Listener... ");
              status.setOpaque(true);
              status.setBackground(Color.RED);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setSize(new Dimension(204, 115));
              frame.setContentPane(status);
              while(true){
                   boolean isGood = listener.getIsGood();
                   if(isGood){
                        status.setBackground(Color.GREEN);
                   else{
                        status.setBackground(Color.RED);
                   try{
                        Thread.sleep(1000);
                   }catch(Exception E){
                        E.printStackTrace();
    }

  • Controlling a thread from the gui

    Hi ive written a small piece of code that demonstrates the problem im having:
    package Util;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class Monitor implements ActionListener {
         Mon mon = new Mon();
         public Monitor() {
              JFrame frame = new JFrame();
              JButton start = new JButton("Start");
              JButton pause = new JButton("Pause");
              pause.addActionListener(this);
              start.addActionListener(this);
              frame.setLayout(new FlowLayout());
              frame.add(start);
              frame.add(pause);
              frame.setVisible(true);
              frame.pack();
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand() == "Start") {
                   mon.start();
              } else {
                   mon.pause();
         public static void main(String args[]) {
              new Monitor();
    class Mon extends Thread {
         public void run() {
              while (true) {
                   System.out.println("Running...");
                   try {
                        sleep(1000);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
         public synchronized void pause() {
              try {
                   wait();
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }I was wondering whether anyone could help me fix this or point out where im going wrong. Whenever the pause button is pressed, i want the thread to temporarily stop printing out "Running" until start is pressed again. At the mo, when i press the pause button, the gui locks up and the thread continues to print out running.
    Cheers.

    Thanks da.futt your advice helped me solve the problem, working example:
    package Util;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class Monitor implements ActionListener {
         Mon mon = new Mon();
         public Monitor() {
              JFrame frame = new JFrame();
              JButton start = new JButton("Start");
              JButton pause = new JButton("Pause");
              pause.addActionListener(this);
              start.addActionListener(this);
              frame.setLayout(new FlowLayout());
              frame.add(start);
              frame.add(pause);
              frame.setVisible(true);
              frame.pack();
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand() == "Start") {
                   try {
                        mon.start();
                   } catch (Exception ex) {
                        mon.restart();
              } else {
                   mon.pause();
         public static void main(String args[]) {
              new Monitor();
    class Mon extends Thread {
         private boolean running = true;
         public void run() {
              while (true) {
                   if (running) {
                        System.out.println("Running...");
                        try {
                             sleep(1000);
                        } catch (InterruptedException e) {
                             e.printStackTrace();
                   } else {
                        synchronized (this) {
                             try {
                                  wait();
                             } catch (InterruptedException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
         public void restart() {
              running = true;
              synchronized (this) {
                   notify();
         public void pause() {
              running = false;
              synchronized (this) {
    }

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Thread synchronize with GUI controls

    I need to modify some GUI controls (append text to JTextArea) from my custom thread..
    Javadoc say that the method append of JTextArea is thread-safe, but if I call it from my thread the application go in blocking-state
    So I try to use, SwingUtilities.invokeLater but when I try to append some text to JTextArea, the application go in blocking-state..
    How can I do for synchronize method call from my thread to main thread..?
    Thanks..

    This is my code:
    private void WriteDebugSafe(final String str)
              Runnable WriteText = new Runnable()
         public void run()
         debug.append(str+"\n");          
         SwingUtilities.invokeLater(WriteText);                    
    After the call to invokeLater.. the application go in blocking-state.
    This appened sometimes.. NOT systematically..

  • Thread issue - Unresponsive GUI

    Hi,
    I am having trouble with threading in an applet. The GUI is pretty much just a JTable. When the user changes values in the JTable, an HttpURLConnection is used to post the changes to the server, and then receive the results of the change from the server, at which point other cells in the JTable will be updated.
    For larger tables (about 2000 cells), the server takes about 20 seconds to do all the calculations. I have the HttpURLConnection work on another thread, and I set the priority of this thread really low when waiting for the response from the server:
    <pre>
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY)
    BufferedReader br = new BufferedReader(new InputStreamReader(
    uc.getInputStream()));
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
    </pre>
    However, during the 20 seconds the server is calculating, the GUI in the applet is very unresponsive - it takes several seconds after a click on the table for the clicked cell to highlight, etc...
    Does anyone have any ideas as to why this might be?

    Hi,
    I am having trouble with threading in an applet. The
    GUI is pretty much just a JTable. When the user
    changes values in the JTable, an HttpURLConnection is
    used to post the changes to the server, and then
    receive the results of the change from the server, at
    which point other cells in the JTable will be
    updated.
    For larger tables (about 2000 cells), the server takes
    about 20 seconds to do all the calculations. I have
    the HttpURLConnection work on another thread, and I
    set the priority of this thread really low when
    waiting for the response from the server:
    <pre>
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY)
    BufferedReader br = new BufferedReader(new
    InputStreamReader(
    uc.getInputStream()));
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY
    </pre>
    However, during the 20 seconds the server is
    calculating, the GUI in the applet is very
    unresponsive - it takes several seconds after a click
    on the table for the clicked cell to highlight,
    etc...
    Does anyone have any ideas as to why this might be?It sounds like you are blocking the event dispatch thread. Can you describe in detail how you are creating the separate Thread to do the work?
    Jim S.

  • Thread wont update GUI component

    I'm developing an RMI application. I can't seem to get the gui components to show their value once their value has been set. I know the value has been set because i can retrieve it and print it out using System.out.println("Client status : " + lblYourStatus.getText());
    My thread gets called when there's a Property ChangeEvent, the code executes correctly but the gui component still doesn't show the correct value.
    Am i implementing the code for the thread incorrectly? or am i missing something else?
    Any help would be appreciated, this has been wrecking my head for a while now.
    private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
    System.out.println("in propertyChange()");
    // lblYourStatus.setText(clientStatus);
    Thread t = new Thread(this);
    t.setDaemon(true);
    t.start();
    public void run()
    // while (true)
    try
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    lblYourStatus.setText(clientStatus);
    System.out.println("Client status : " + lblYourStatus.getText());
    catch (Exception e)
    try
    Thread.sleep(1000);
    catch(Exception e) {}
    // } //end while
    }

    I don't think the RMI can affect it. It's the same for one client as it is for multiple clients. All the clients receive the correct values. I have been using System.out.println() statements to follow the program as it's been executing and everything seems to work as it should. I changed the code using the example you directed me to.
    It still receives all the correct values but when i set the label text the gui still doesn't show the text if i pass it in as a variable eg lblPlayer1Name.setText(m_player1Name), it still shows literal values eg lblPlayer1Name.setText( "test")
    I know the variable names contain valid values as i use System.out.println() statements to view them.
    any more ideas? thanks for your help so far.
        private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
            Thread t = new Thread(this);
           // t.setDaemon(true);
            t.start();
        public void updateDetails(boolean gameInProgress, String status, String player1Name, String player2Name, int numSpectators)
            m_clientStatus = m_clientStatus + status;
            m_player1Name = player1Name;
            m_player2Name = player2Name;
            lblYourStatus.setText(m_clientStatus);       
            lblPlayer1Name.setText(m_player1Name);
            lblPlayer2Name.setText(m_player2Name);
        public void run()          
            //  SwingUtilities makes sure code is executed in the event thread.                                        
            SwingUtilities.invokeLater(new Runnable()                              
                public void run()                              
                    //this line wont print the value to the screen eventhough the next System.out.println() statement shows that the variable contains a valid string                              
                    lblPlayer1Name.setText(m_player1Name);     
                    System.out.println("Player 1 variable value: " + m_player1Name);
                    System.out.println("Player 1 label value: " + lblPlayer1Name.getText());
                    lblPlayer1Name.setText(lblPlayer1Name.getText());
                    //this line will print the literal string "Tom" to the label
                    lblPlayer1Name.setText("Tom");     
            // simulate log running task                              
          //  try { Thread.sleep(1000); }                         
          //  catch (Exception e) {}                    
            SwingUtilities.invokeLater(new Runnable()               
                public void run()                              
                    lblPlayer2Name.setText(m_player2Name);
                    System.out.println("Player 2 variable value: " + m_player2Name);
                    System.out.println("Player 2 label value: " + lblPlayer2Name.getText());
        }

  • How to create a JTree in a separate thread?

    Hi. I am writing a Swing application which has a JTree that is made up of company parent nodes and employee child nodes. My problem is that the data for this JTree is loaded from the database and this process takes a long time making the loading time of the app too slow. I think that this process should probably be done in a separate thread. This would let the gui load much quicker and then when the thread finishes it can update the graphics to display the JTree. I have the code for the JTree all done and it works but I need help on putting it in a separate thread and running the thread. I am having trouble with this. Any help would be greatly appreciated.
    Eugene P.

    Thank you for responding to my question but I actually figured out a solution already. I used the SwingWorker class. When the program loads I just display a simple JTree with just the names of the companies without the employees. This takes almost no time to load. Then in the construct() method of the SwingWorker class I run the query to get the employee names and then create the new JTree that has the firms and the employees. In the finished() method of the SwingWorker class I update the gui. This whole process is running in a separate thread while the gui is already loaded so it works beautifully.

  • GUI ..Process and threads

    Hi..Folks
    Is it possible to read the output of a class by starting it as a separate thread in a GUI application?
    Currently we follow this approach. We start the class as a separate process (passing in what ever parameters needed) in the GUI(using RunTime.exec()). Read the output.
    But we need a reference to the class that is being started.
    Is it possible to get a reference to the class?
    Thanks in advance.

    Thanks for your replies.
    Oki this time i will be more specific..I want to start and read the output of a thread..So while the thread is executing I can hook in to the output stream and read the output simultaneously...Actually I came across this link [Convert a Java OutputStream to an InputStream|http://ostermiller.org/convert_java_outputstream_inputstream.html] ... which suggests some idea to it...But the code gives compilation error (the bold line) ..."Cannot refer to a non-final variable in inside an inner class defined in a different method"..I have attached the code..Any ideas?
    Readin.java creates the thread and sends in the PipedInputStream to tt.java's putDataOnOutputStream() which writes to the stream back...
    Readin.java
    byte[] b = null;
               PipedInputStream in = new PipedInputStream();
               PipedOutputStream out ;
              try {
                   out = new PipedOutputStream(in);
              } catch (IOException e) {
                   e.printStackTrace();
                new Thread(
                  new Runnable(){
                    public void run(){
                      try {
                        *     new tt().putDataOnOutputStream(new PipedOutputStream(in));*
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                ).start();
               try {
                   in.read(b);
              } catch (IOException e) {
                   e.printStackTrace();
               String str = new String(b);
               System.out.println(str);
    ...          And the code for the other class is
    ... tt.java.....
    public  void putDataOnOutputStream(ByteArrayOutputStream out){
              String str="test";
              try {
                   out.write(str.getBytes());
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }

  • Is it possible to seperate an ActiveX control from the GUI thread?

    I have an activeX control (*ocx) that we use for communicating with external instruments. We are running into some difficulty because if the communication with the instrument is held up it can take up to 30 seconds to timeout and our LabVIEW user interface is frozen in the mean time. The VI that contains the control itself does not have to be visible and all the subVIs that use the ActiveX reference have been set to run in the "instrument" execution system thread, but the GUI still freezes. Its my theory that since the ActiveX control itself is in a container and part of a front panel, all refernces to it must be executed in the GUI thread. I just wanted to confirm that this was the case. Also if anyb
    ody would like to suggest any work arounds, feel free. The only idea I've had so far was to move all use of the ActiveX control to external code, which is not a very attractive solution for us.

    ....Also if anybody would like to suggest any work arounds,
    > feel free. The only idea I've had so far was to move all use of the
    > ActiveX control to external code, which is not a very attractive
    > solution for us.
    ActiveX controls are loaded into the UI thread and all interactions with
    them, property nodes, and invoke nodes, have to take place in the UI
    thread/main thread of LV. So, setting the VIs to run in the
    instrumentation or other execution systems, doesn't do much good since
    each call to the property or invoke will just have to switch back.
    What other choices do you have? If the control doesn't have a UI
    anyway, it would improve matters if the control were simply an
    automation server. The automation server can be set to run in a single
    thr
    eaded apartment, or a MT apartment. Changing it to MT means that you
    will have to deal with protecting the code from being called from
    different threads, and having those calls interleaving and competing
    with one another. When you change it to be MT, it can tie up other
    threads in LV and leave the UI thread alone. Another alternative is to
    change the ActiveX control to spin up its own thread and have a method
    that initiates, and one that reads the results or returns the status.
    Greg McKaskle

  • Display JTree in browser using JSP

    i have a program that converts xml file in to tree structure(using Swing). When i run this using eclipse then it is working. Swing is an extension of applet , right. I want to embed this in an HTML page(JSP). so that i can display the tree structure. Its gives class not foung error.
    It is not posiible to embed it. I think if it extends an Applet then it will display. But i don't know how to convert that. It gives error if i convert.
    pls help
    CODE:
    package TreeGen;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import java.io.IOException;
    import org.w3c.dom.Document;
    // Basic GUI components
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    // GUI components for right-hand side
    import javax.swing.JSplitPane;
    import javax.swing.JEditorPane;
    // GUI support classes
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    // For creating borders
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    // For creating a TreeModel
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    public class TreeGen extends JPanel
         static Document document;
         boolean compress = false;
         static final int windowHeight = 660;
         static final int leftWidth = 300;
         static final int rightWidth = 640;
         static final int windowWidth = leftWidth + rightWidth;
         public TreeGen()
         EmptyBorder eb = new EmptyBorder(5,5,5,5);
         BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
         CompoundBorder cb = new CompoundBorder(eb,bb);
         this.setBorder(new CompoundBorder(cb,eb));
         JTree tree = new JTree(new DomToTreeModelAdapter());
         JScrollPane treeView = new JScrollPane(tree);
         treeView.setPreferredSize(
              new Dimension( leftWidth, windowHeight ));
         final
         JEditorPane htmlPane = new JEditorPane("text/html","");
         htmlPane.setEditable(true);
         JScrollPane htmlView = new JScrollPane(htmlPane);
         htmlView.setPreferredSize(
              new Dimension( rightWidth, windowHeight ));
         tree.addTreeSelectionListener(
              new TreeSelectionListener()
              public void valueChanged(TreeSelectionEvent e)
                   TreePath p = e.getNewLeadSelectionPath();
                   if (p != null)
                   AdapterNode adpNode =
                        (AdapterNode) p.getLastPathComponent();
                   htmlPane.setText(adpNode.content());
         JSplitPane splitPane =
              new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                  treeView,
                                  htmlView );
         splitPane.setContinuousLayout( false );
         splitPane.setDividerLocation( leftWidth );
         splitPane.setDividerSize(1);
         splitPane.setPreferredSize(
                   new Dimension( windowWidth + 10, windowHeight+10 ));
         this.setLayout(new BorderLayout());
         this.add("Center", splitPane );
         //return menuBar;
         } // constructor
         public static void main(String argv[])
              DocumentBuilderFactory factory =
                   DocumentBuilderFactory.newInstance();
              try {
              DocumentBuilder builder = factory.newDocumentBuilder();
              document = builder.parse("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/parser1/sample.xml");
                   makeFrame();
              } catch (SAXException sxe){
                   System.out.println("ERROR");
              Exception x = sxe;
              if (sxe.getException() != null)
                   x = sxe.getException();
              x.printStackTrace();
              } catch (ParserConfigurationException pce) {
                   pce.printStackTrace();
              } catch (IOException ioe) {
              ioe.printStackTrace();
         } // main
         public static void makeFrame()
              JFrame frame = new JFrame("DOM Echo");
              frame.addWindowListener(
              new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {System.exit(0);}
              final TreeGen echoPanel =
              new TreeGen();
              frame.getContentPane().add("Center", echoPanel );
              frame.pack();
              Dimension screenSize =
              Toolkit.getDefaultToolkit().getScreenSize();
              int w = windowWidth + 10;
              int h = windowHeight + 10;
              frame.setSize(w, h);
              frame.setVisible(true);
         } // makeFrame
         static final String[] typeName = {
              "none",
              "Element",
              "Attr",
              "Text",
              "CDATA",
              "EntityRef",
              "Entity",
              "ProcInstr",
              "Comment",
              "Document",
              "DocType",
              "DocFragment",
              "Notation",
         static final int ELEMENT_TYPE = 1;
         static final int ATTR_TYPE = 2;
         static final int TEXT_TYPE = 3;
         static final int CDATA_TYPE = 4;
         static final int ENTITYREF_TYPE = 5;
         static final int ENTITY_TYPE = 6;
         static final int PROCINSTR_TYPE = 7;
         static final int COMMENT_TYPE = 8;
         static final int DOCUMENT_TYPE = 9;
         static final int DOCTYPE_TYPE = 10;
         static final int DOCFRAG_TYPE = 11;
         static final int NOTATION_TYPE = 12;
    static String[] treeElementNames = {
              "slideshow",
              "slide",
              "title", // For slideshow #1
              "slide-title", // For slideshow #10
              "item",
         boolean treeElement(String elementName) {
         for (int i=0; i<treeElementNames.length; i++) {
              //System.out.println(treeElementNames);
              if ( elementName.equals(treeElementNames[i]) )
              return true;
         return false;
         public class AdapterNode
         org.w3c.dom.Node domNode;
         public AdapterNode(org.w3c.dom.Node node)
              domNode = node;
         public String toString()
              String s = typeName[domNode.getNodeType()];
              String nodeName = domNode.getNodeName();
              if (! nodeName.startsWith("#"))
              s += ": " + nodeName;
              if (compress)
              String t = content().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += " " + t;
              return s;
              if (domNode.getNodeValue() != null)
              if (s.startsWith("ProcInstr"))
                   s += ", ";
              else
                   s += ": ";
              // Trim the value to get rid of NL's at the front
              String t = domNode.getNodeValue().trim();
              int x = t.indexOf("\n");
              if (x >= 0) t = t.substring(0, x);
              s += t;
              return s;
         public String content()
              String s = "";
              org.w3c.dom.NodeList nodeList = domNode.getChildNodes();
              for (int i=0; i<nodeList.getLength(); i++)
              org.w3c.dom.Node node = nodeList.item(i);
              int type = node.getNodeType();
              //System.out.println(type);
              AdapterNode adpNode = new AdapterNode(node); //inefficient, but works
              if (type == ELEMENT_TYPE)
                   if ( treeElement(node.getNodeName()) ) continue;
                   s += "<" + node.getNodeName() + ">";
                   s += adpNode.content();
                   s += "</" + node.getNodeName() + ">";
              else if (type == TEXT_TYPE)
                   s += node.getNodeValue();
              else if (type == ENTITYREF_TYPE)
                   s += adpNode.content();
              else if (type == CDATA_TYPE)
                   StringBuffer sb = new StringBuffer( node.getNodeValue() );
                   for (int j=0; j<sb.length(); j++)
                   if (sb.charAt(j) == '<')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "lt;");
                        j += 3;
                   else if (sb.charAt(j) == '&')
                        sb.setCharAt(j, '&');
                        sb.insert(j+1, "amp;");
                        j += 4;
                   s += "<pre>" + sb + "\n</pre>";
              return s;
         public int index(AdapterNode child)
              int count = childCount();
              for (int i=0; i<count; i++)
              AdapterNode n = this.child(i);
              if (child.domNode == n.domNode) return i;
              return -1; // Should never get here.
         public AdapterNode child(int searchIndex)
              org.w3c.dom.Node node =
                   domNode.getChildNodes().item(searchIndex);
              if (compress)
              int elementNodeIndex = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
                   node = domNode.getChildNodes().item(i);
                   if (node.getNodeType() == ELEMENT_TYPE
                   && treeElement( node.getNodeName() )
                   && elementNodeIndex++ == searchIndex)
                   break;
              return new AdapterNode(node);
         public int childCount()
              if (!compress)
              return domNode.getChildNodes().getLength();
              int count = 0;
              for (int i=0; i<domNode.getChildNodes().getLength(); i++)
              org.w3c.dom.Node node = domNode.getChildNodes().item(i);
              if (node.getNodeType() == ELEMENT_TYPE
              && treeElement( node.getNodeName() ))
                   ++count;
              return count;
         public class DomToTreeModelAdapter
         implements javax.swing.tree.TreeModel
         public Object getRoot()
              return new AdapterNode(document);
         public boolean isLeaf(Object aNode)
              AdapterNode node = (AdapterNode) aNode;
              if (node.childCount() > 0) return false;
              return true;
         public int getChildCount(Object parent)
              AdapterNode node = (AdapterNode) parent;
              return node.childCount();
         public Object getChild(Object parent, int index)
              AdapterNode node = (AdapterNode) parent;
              return node.child(index);
         public int getIndexOfChild(Object parent, Object child)
              AdapterNode node = (AdapterNode) parent;
              return node.index((AdapterNode) child);
         public void valueForPathChanged(TreePath path, Object newValue)
         private Vector listenerList = new Vector();
         public void addTreeModelListener(TreeModelListener listener)
              if ( listener != null
              && ! listenerList.contains( listener ) )
              listenerList.addElement( listener );
         public void removeTreeModelListener(TreeModelListener listener)
              if ( listener != null )
              listenerList.removeElement( listener );
         public void fireTreeNodesChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesChanged( e );
         public void fireTreeNodesInserted( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesInserted( e );
         public void fireTreeNodesRemoved( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeNodesRemoved( e );
         public void fireTreeStructureChanged( TreeModelEvent e )
              Enumeration listeners = listenerList.elements();
              while ( listeners.hasMoreElements() )
              TreeModelListener listener =
                   (TreeModelListener) listeners.nextElement();
              listener.treeStructureChanged( e );

    I actually had to do this a few months ago. There are ways to perform this kind display using various distributed object (i.e., using MS Word OLE objects to "interpret" the byte for you, etc.). But this soon got extremely difficult to manage (and I actually had to use Perl/CGI for the majority of it).
    The solution I went with was to implement a "cache" directory on the web server. Basically, the JSP/Servlet can simply check the cache and if file not there, create it from the database. Then send a redirect back to the browser to this newly-created file. The browser will then appropriately open the document. I tested this with both Netscape and IE browsers and common MIME types such as text files, MS Office docs, zip files, PDFs, RTFs.
    Not ideal, but unfortunately the best I came up with.

  • Calls to methods in a class that extends Thread

    Hello,
    I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
    The code to my class is as follows:
    public class FullURLAddress
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
    public class FullURLAddress extends Thread
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
      public void run()
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    /* What happens with these methods, will they need to have their
    own treads also? */
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
    Please explain.
    This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
    Thanks
    Davo

    Threads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
    So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
    You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
    One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
    Here is a java thread tutorial, worthy reading:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • Find out how many threads in a Java program

    Why do I get ID 20, ID 21, ID 22 by runing the following code? I would like to know if i acturely create a thread then stop it probably. somehow i need to call it two more times in my program.
    start() and interrrupt() are default thread methods. when I call start() it goes to my run() method. I am worry about if the thread 20 and 21 are still doing something after creating thread 22
    main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;
            main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;
            main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;

    Here is my code, I would like to know if I implement my threads nicely here, I am worrying those threads are still alive, they should be interrupted. but why I got different thread ID, when i resume it?
    // Two player board game play in turn. Human plays first as red, the computer plays
    // second as blue. I used thread here for repainting the applet, because the computer
    // evaulation function is quite slow, the gui won't draw human player's move until it
    // finishs calculating computer's move. the solution i use is interrupting the current
    // thread, let the gui repaint before calculating the computer move.
    // Board.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends Canvas implements Runnable, MouseListener {
        private Thread main;
        private int state = 0;
        private double aMove = 0;
        public void init() {
            addMouseListener(this);
        public void run() {
            removeMouseListener(this);
            main.interrupt();
            main = null;
            repaint();
            // calculate computer's move, then making move
            // this is a slow evalution function goes here
            for (int i = 0; i <10000000; i++) {
                aMove = Math.pow(0.1,1000000000);
            state = 1;
            repaint();
            System.out.println("Blue makes a move on postion " + aMove);
            state = -1;
            addMouseListener(this);
        public void paint(Graphics g) {
            System.out.println("paint");
            if (state == 1) {
                g.setColor(Color.blue);
                g.fillOval(0, 0, 20, 20);
            if (state == -1) {
                g.setColor(Color.red);
                g.fillOval(0, 0, 20, 20);
        public void mouseReleased(MouseEvent e) {
            // human player makes a move on postion 0;
            aMove = 0;
            System.out.println("Red makes a move on postion " + aMove);
            state = -1;
            repaint();
            // Why the following gives me different thread here every time?
            main = new Thread(this);
            System.out.println("Thread ID: "+ main.getId());
            main.start();
        public void mousePressed(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mouseClicked(MouseEvent e) {
    // appletdemo.java
    import java.applet.*;
    import java.awt.*;
    public class appletdemo extends Applet{
        Board b = new Board();
        public void init() {
            System.out.println("start ");
            setLayout(new BorderLayout());
            this.add(b);
            b.init();
            setVisible(true);
    }

Maybe you are looking for

  • QM-IDI, upload functions

    Hello QM masters, Iu2019m trying to use the QM-IDI, but Iu2019m having some difficulties with the function modules to update the characteristic results. I tried to use the function module QIRF_GET_ORIGINAL_VALUES2 and QIRF_GET_FEATURE_VALUES2 and I g

  • Jar files for Maxdb????

    Could some one advise if we need jar files for Maxdb using SAP-XI. Do they have to be deployed on the XI server. If yes what are the jar files necessary. Thanks in advance

  • Help troubleshooting ORA-31003 when granting privilege

    Hi All I'm stumped on this. I need to enable network services for APEX_030200 using the script provided by Oracle. I've read many metalink docs and forums etc... Spent hours(days...) troubleshooting so any help would be greatly appreciated. We reload

  • How to maintain a counter column?

    Hi All, I am a novice with Oracle. Currently I have a problem which requires me to maintain a counter in an oracle column. Following is my schema: assetTable 1. ID 2. Name 3. Count recordTable 1. ID 2. AssetID For each insert in the recordTable, I wa

  • Mask on PDF

    Hi everybody, I do have a nice pages - document with a so called "mask", a picture with blurred edges. Now I want to export this document into a PDF file. Then the egdes of the mask are unfortunately not blurred anymore. How can I avoid this? Regards