Threads + Swing

Hi folks,
I found the following code here at SDN. The main purpose of this code is to execute an exe-file and to redirect its output to a java Swing JTextArea.
This code works fine. However, if I change...
    public cCallGenerator()
        init();
        initProcess();
    }...to...
    public cCallGenerator()
        init();
        // initProcess(); NOW WE DONT START THE PROCESS HERE
    }and start initProcess() by clicking on the button, the output is NOT(!) redirected to the JTextArea. The exe file is still running.
I guess that I simply misunderstood the concept of threads in java...
Can anybody help me?
Thanks a lot
Christian
Here is the code:
import javax.swing.*;
import org.dom4j.Document;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
public class cCallGenerator extends JFrame {
    private JTextArea textArea;
    private JTextField textField;
    private PrintWriter writer;
    public cCallGenerator()
        init();
        initProcess();
    public void init()
        textArea = new JTextArea(20, 80);
        textArea.setEditable(false);
        textField = new JTextField(30);
        textField.addKeyListener(new KeyAdapter()
            public void keyPressed(KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.VK_ENTER)
                    if (writer != null)
                        textArea.setText("");
                        writer.print(textField.getText() + "\r\n");
                        writer.flush();
                        textField.setText("");
        Container container = getContentPane();
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(textArea);
        container.add(scrollPane, BorderLayout.CENTER);
        container.add(textField, BorderLayout.SOUTH);
        JButton start = new JButton("Start");
        container.add(start, BorderLayout.WEST);
                                   start.addActionListener(new ActionListener() {
                                        public void actionPerformed(ActionEvent evt) {
                                             try {
                                                  initProcess();
                                             } catch(Exception e) {
                                                  JOptionPane.showConfirmDialog(null,
                                                            "The following error occured while trying to generate the configuration file: \n\n" + e.getMessage(),
                                                            "XML Error",
                                                            JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);     
                                                  System.exit(1);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        textField.grabFocus();
        setVisible(true);
    public static void main(String[] args) {
        new cCallGenerator();
    public void initProcess()
        Runtime rt = Runtime.getRuntime();
        try
            //Process p = rt.exec(new String [] {"cmd", "/C", textField.getText()});
            //textArea.setText("");
            //textField.setText("");
            Process p = rt.exec("panoratio.exe -g -c output.xml -o output.pdi");
            writer = new PrintWriter(p.getOutputStream());
            Thread thread1 = new Thread(new StreamReader(p.getErrorStream()));
            Thread thread2 = new Thread(new StreamReader(p.getInputStream()));
            thread1.start();
            thread2.start();
            System.out.println("Exit Value = " + p.waitFor());
        catch (Exception ex)
            textArea.append(ex.getMessage());
            ex.printStackTrace();
    public class StreamReader implements Runnable
        InputStream is;
        public StreamReader(InputStream is)
            this.is = is;
        public void run()
            try
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String data;
                while ((data = reader.readLine()) != null)
                    textArea.append(data + "\n");
                reader.close();
            catch (IOException ioEx)
                ioEx.printStackTrace();
}

Thanks for your help!
I still don't really understand why - but if I replace
            thread1.start();
            thread2.start();with
            thread2.start();
            SwingUtilities.invokeAndWait(thread1);it works. So, thanks a lot for your help.
Bye

Similar Messages

  • Threading Swing, is this correct?

    Hey guys
    Ive just done a little swing window, that is thread safe... well i think it is, im asking you guys if this is the correct way to create a swing app (composition rather than inheritance) and if i add more comonents will they each (e.g JButton) need to be implemented as threads?
    any help and your experience would be great
    cheers
    This is the code for a simple window, Is it how you pros would do it?:
    import javax.swing.JFrame;
    import java.lang.*;
    public class UI implements Runnable
    private JFrame wnd = new JFrame("CLIENT");
    public void createWnd()
    wnd.setSize(400, 400);
    wnd.setDefaultCloseOperation(wnd.EXIT_ON_CLOSE);
    wnd.setVisible(true);
    public void run()
    createWnd();
    System.out.println("Thread started");
    public boolean closed()
    if((wnd.getDefaultCloseOperation()) == wnd.EXIT_ON_CLOSE)
    return true;
    return false;
    //System.out.println("pressed closed");
    public static void main(String[] args)
    UI appWindow = new UI();
    Thread t = new Thread(appWindow);
    t.start();
    if(appWindow.closed())
    t = null;
    System.out.println("Thread stopped");
    } Message was edited by:
    FatClient

    So the reason that a swing application needs to be on
    the EDT of each swing UI (and not on a user thread)
    is because thats the queue that holds keystrokes,
    mouse clicks, etc that may need the UI to be redrawn
    after an event.
    And if you had other code going on, this would not be
    interrupted/paused whilst the EDT/GUI were working to
    redraw a bit of the app - Bcause it is in a THREAD.Swing sets up the EDT (Event Dispatch Thread), and what it does is
    pretty simple: it dequeues swing events like mouse events and
    keyboard events, etc... and causes the appropriate listener methods
    to be called. So for example, ActionListener's actionPerformed methods
    are going to be called on the EDT (if you coded correctly).
    In Java you are free to create other threads, but you always have to
    be careful when multiple threads access common data. In the case
    of Swing, to keep its implementation as simple as possible, most
    Swing methods are meant to only be called from the EDT.
    Please let me know if thats why i should blindly
    listen to the JDK tutorials as if it were some sort
    of bible/Torah/Quran The Java Language Specification (JLS) is the Koran. The tutorials are the Hadith :-)

  • Threads + Swing = Confusion

    Hi all,
    I am having a problem with threads and Swing apps. I have read the tutorial 3 times and get more confused each time i try to understand how to update the gui with the other thread.
    At this point I'm just trying to do something simple (eventually i want the gui to report all the progress of the action): get a progress bar to be updated through a Thread Class. I have the gui built with a button and a progress bar. Here is the codei have for the simpleThread class
    import java.awt.*;
    import javax.swing.*;
    public class simpleThread extends Thread{
        public simpleThread(String str) {
            super(str);
        public void run() {
            for (int i = 0; i<1000000; i++) {
                final int x = i;
                Runnable getTextFieldText = new Runnable() {
                    public void run() {
                       jProgressBar1.setValue(x);
        SwingUtilities.invokeAndWait(getTextFieldText);
    }The problem i have is that the thread doesn't recognize the gui form. Any help on getting the progress bar to update with the thread would be great! Thanks! :)

    There's been too much bad code submitted to this topic to comment on it individually, but:
    1. Don't call a thread or runnable's run() method directly, if you expect it to be executed in a different thread! Call thread's start method instead.
    2. If you want code executed in the Event Dispatch Thread (EDT), pass a runnable to InvokeLater (usually preferrable to InvokeAndWait). That runnable's run method will be executed in the EDT -- there's no need to write complicated nested run methods!
    In the case of JProgressBar, I was concerned about flooding the EDT with many "invokeLater" runnables, so I penned this wee class:
    import javax.swing.*;
    public class Updater  {
         private final JProgressBar jpb;
         private boolean queued;
         private int val;
         private Runnable runnable = new Runnable() {
              public void run() {//called from EDT:
                   int _val;
                   synchronized(Updater.this) {
                        queued = false;
                        _val = val;
                   jpb.setValue(_val);
         public Updater(JProgressBar jpb) {
              this.jpb = jpb;
         public void update(int _val) {
              boolean go = false;
              synchronized(this) {
                   val = _val;
                   if (!queued) {
                        queued = true;
                        go = true;
              if (go)
                   SwingUtilities.invokeLater(runnable);
    }To use it, you would typically declare it as a field:
    private Updater updater = new Updater(yerBar);Then repeatedly call (from any thread)
    updater.update(yerValue);

  • Threaded swing applet

    Hi,
    I need to write an applet that shows the results of a database query on a JTable.
    The query will be executed every second (only a few registers are retrieved from a mySQL db), and if a change is detected, the JTable must be updated.
    I've been reading about Swing and threads, and I know I must be careful when workin with threads on my GUI.
    So far, I know there exists a few methods to perform what I need, but I'm not shure which one would be the best for my app.
    The methods I'm considering are:
    - invokeLater or invokeAndWait
    - timer
    - SwingWorker
    What do you guys sugest and why ?
    Thanks

    Not sure of this, but I think you need both Timer (to query DB every second) and SwingUtilities.invokeLater (because your update task must be run outside of EDT)...
    Hope this helped a little,
    Regards.

  • Thread+Swing

    Iam developing a program which involves setting up an auction bid system. The application creates threads to service clients which send in bids. There is a GUI which displays the IP address, the time of bid and the bid amount. The application threads write to a shared buffer and Iam using a swing timer to automatically generate action events to read from the shared buffer. Iam using Semaphores to syncronize the access to the shared buffer. The trouble is that the GUI seems to go "dead". I can't click on the buttons on it . Iam new to java and would appreciate any help on this

    Post the code. Your description is far to vague to be of help.

  • Threads, swing etc...

    Hi, I need to develop a software that manage the windows creation. Each windows make some operation: eg. show or manage some data or is a text editor and so on.. I need to know the general idea that is behind the design of a software of this type. I make myself more clear: I don't know the startup, if I need to make a tread manager and use a thread for each window, or use some kind of design pattern for manage this situation.
    Someone has the expertise for explain this such of problem?

    The systematic difference in GUI programming as opposed to a simple command line program is that it's handled as events. An event usually represents a user action (sometimes it's a timer or the like). You provide code to handle that event, which may result in a change in what is displayed. But once you've handled an event your handler code finishes and the system goes back to waiting for the next event.
    In an ordinary program there's a definite sequence to be executed, in a GUI program the program spends most of it's time waiting for the user to decide what he wants to do next.
    However sometimes an event launches an activity which runs for some time in the background and, when it's ready, changes the display. These activities are called "worker threads" and have more resemblance to ordinary programs.
    The GUI event processing occurs as a loop on a single thread, and only one event is processed at a time. This means event handlers must finish quickly, to let other events proceed. An event that launches an action that is likely to take more than a fraction of a second should start a worker thread.

  • Memory Leak in a multi threaded Swing application  (ImageIcon)

    When I profile my swing application with netbeans 5.5 , I notice that after each periodically tidy up my image container (add,remove IconImage objects to a hashmap or arraylist), there gather by and by surviving objects. This leads to run out of memory after a while. Is there any other way to avoid this effect?
    Any ideas about "The JVM is notorious for caching images."
    please help..
    what I have made briefly:
    1.) Read the binary stream from the db :
    rs=stmt.executeQuery(query);
    if(rs.next()){
        int len=rs.getInt(2);
        byte [] b=new byte[len];
        InputStream in = rs.getBinaryStream(3);
        try {
                in.read(b);
                in.close();
                img=Toolkit.getDefaultToolkit().createImage(b);
         } catch (IOException e) {
                e.printStackTrace();
    stmt.close();
    rs.close();2.) hold the icon as field :
    this.icon =  new ImageIcon(img);3.) After a while I remove the object from my collection and on the
    overridden method finalize() I also call the flush() method.
    if(this.icon != null){
                this.icon.getImage().flush();
                this.icon = null;
    }The surviving objects still increase?! On the page of SUN they
    submitted a bug. But this is set on closed/fixed.
    (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4014323)
    What am I doing wrong? I also use the byte[] constructor on creating the icon and
    my java version is 1.5.0_10.

    If in your JFrame u have placed your image, before invoke the dispose()
    method put explicitly the image pointer to null and deregister all listener
    you have added to any componentI implemented your suggest and after starting a long time test, in one hour there gathered aprox. 500 surviving generations. I attach a snapshot and the java file ( http://www.box.net/public/eqznamrazd ). The used heap size swings between 3MB and 5MB. I guess this wont kill so quickly the application but anyway there is something wrong!
    Even properly closed streams, database connections etc.. Really despairing. Could one take a look to the java source?
    some snippets bellow:
    private class MyImageIcon extends ImageIcon {
            public MyImageIcon(Image img){
                super(img);
            public void removeImage(Image anImage){
                tracker.removeImage(anImage);
    private class DetailDialog extends javax.swing.JFrame {
            private String personnr;
            private MyImageIcon icon;
            public DetailDialog(String personnr,MyImageIcon icon){
                this.personnr = personnr;
                this.icon = icon;
            public void dispose() {
                if(icon != null){
                    icon.removeImage(icon.getImage());
                    icon.getImage().flush();
                    icon = null;
                super.dispose();
    private class Person extends Object {
            private MyImageIcon icon;
            private String number;
            private DetailDialog detailDialog;
            protected void destroy() {
                if(icon!=null){
                    icon.removeImage(icon.getImage());
                    icon.getImage().flush();
                    icon = null;
                if(detailDialog!=null){
                    detailDialog.dispose();
    private Image LoadImageFromDB(String personnr){
            Image img = null;
            String filename = personnr + ".jpg";
            Connection con = getMysqlConnection();
            Statement stmt;
            ResultSet rs;
            try {
                stmt = con.createStatement();
                String query = "select * from personImage where image='"+filename+"'";
                rs=stmt.executeQuery(query);
                if(rs.next()){
                    int len=rs.getInt(2);
                    byte [] b=new byte[len];
                    InputStream in = rs.getBinaryStream(3);
                    try {
                        in.read(b);
                        in.close();
                        img =
                                java.awt.Toolkit.getDefaultToolkit().createImage(b);
                    } catch (IOException e) {
                        e.printStackTrace();
                rs.close();
                rs = null;
                stmt.close();
                stmt = null;
                con.close();
                con = null;
            } catch (SQLException e) {
                e.printStackTrace();
            return img;
    public void random(){
            java.sql.ResultSet rs = null;
            java.sql.Statement stmt=null;
            java.sql.Connection con = getSybaseConnection();
            try {
                try {
                    stmt = con.createStatement();
                    rs = stmt.executeQuery(randomquery);
                    while(rs.next()){
                        Person person = new Person();
                        person.number = rs.getString("PersonNr");
                        Image img = LoadImageFromDB(person.number);
                        if(img !=null){
                            MyImageIcon ico = new MyImageIcon(img);
                            person.icon = ico;
                        person.detailDialog = new
                                DetailDialog(person.number,person.icon);
                        personList.add(person);
                        System.out.println("Container size: " +
                                personList.size());
                        counter++;
                    if(counter%20 == 0){
                        for(Person p : personList){
                            p.destroy();
                        personList.clear();
                        System.gc();//no need, but I force for this example
                        System.out.println("Container cleared, size: " +
                                personList.size());
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }finally{
                    if(rs != null){
                        rs.close();
                    }if(stmt != null){
                        stmt.close();
                    }if(con != null){
                        con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
        }

  • Stringtokenizer, swing and memory

    i lately found that the stringtokenizer eats up lots of memory, i tried to set vars to null and called sys gc quite often but they didnt seem to be of much help.
    ok, here is what i was doing: i read in a quite a big txt file, about 400k lines, and then parsed each line using stringtokenizer, everything happened in while loops, lots of objects but all small ones. i had to xmx lots of memories to it in order to run it. and it became much worse when i put it into multi threaded swing app. if you are a swing expert, or stringtokenizer expert, please shed some light.

    Dang it! Sun zapped a bunch of posts!
    Anyway, here again is a sample pgm posted earlier (which got zapped) showing some of the benefits of the finally block, for which the idiot daFei could not come up with an intelligent answer to refute it (he STILL has a beef with the finally block, claiming it is only "syntactic sugar", and still moronically implies that all methods must handle all exceptions, which is absurd in that no exceptions could ever be THROWN then!)
    import java.io.File;
    import java.io.IOException;
    class SillyQuestionException extends Exception {
      public SillyQuestionException() {
        super("That's a silly question.  Of course!");
    class Guru {
       * Responds to a question/statement.  A temporary file is created
       * during execution, and deleted upon return (unless daFei dorks
       * with the implementation!)
       * @param request the question/statement for Guru to respond to
       * @return the Guru's response
       * @throws SillyQuestionException if the Guru determines you're
       * asking a silly question,
       * to which the answer should be obviously YES
      public static String respond(String request)
        throws SillyQuestionException {
        File f = new File("daFei.is.an.idiot");
        try {
          System.out.println("  Guru is thinking...");
          f.createNewFile();
          // let's just assume we needed to write stuff to this file in
          // order to process the request...
          // now the actual end of processing
          if ("is daFei an idiot".equals(request))
            throw new SillyQuestionException();
        catch (IOException e) {
          System.out.println("Error occurred creating/writing to " +
            "temp file, but graceful recovery is possible");
          e.printStackTrace();
          return "I'll have to get back to you on that one.  " +
            "Ask me again later.";
        finally {
          // this is NECESSARY to GUARANTEE deletion of the temp file,
          // otherwise this statement would have to be duplicated at all
          // possible return points.
          System.out.println("  Guru has processed your request...");
          if (f != null)
            f.delete();
        System.out.println("  will this get printed EVERY time?  " +
          "NO IT WILL NOT!");
        return "daFei has fish turds in his brain";
    public class Demo {
      public static void main(String[] args) {
        String[] questions = {
          "what statement best describes daFei",
          "what kind of turds does daFei have in his brain",
          "is daFei an idiot",
          "won't get to this question"
        try {
          for (int i = 0; i < questions.length; ++i) {
            System.out.println("Question: " + questions);
    System.out.println("Response: " + Guru.respond(questions[i]));
    catch (SillyQuestionException e) {
    System.out.println("I have finally asked the Guru a silly " +
    "question, and will stop now");
    System.out.println("Here's what Guru had to say to the last " +
    "question: " + e);

  • Player's position slider (Thread not owner)

    Hi every1,
    I've a thread that sets a slider value with the player's time in secods,but in case the slider Knob is dragged by the user the thread should wait and player's time should be set as per the value dragged by the user.
    But the wait() method is not executing instead it generates IllegalMonitorStateException: current thread not owner exception. Would you help me please?
    My code is:
    //the thread which sets the slider value as the time in second increases
    public void run() {
         while (true) {
                        if (player != null) {
               nano = player.getMediaTime().getSeconds();
              if (dura >nano) {
                  timex = (int)nano;
                        jSlider.setValue(timex);
                     try {
              Thread.currentThread().sleep(1000);
             } catch (InterruptedException ie) {
        }//the method which sets the slider as a user moves the knob of the slider
    jSlider.addChangeListener(new javax.swing.event.ChangeListener() {
                public void stateChanged(javax.swing.event.ChangeEvent evt) {
                   try{
                      if(jSlider.getValueIsAdjusting()){
    player.setMediaTime(new javax.media.Time((double)  
    jSlider.getValue())); 
                    thr.wait();                  }
                   }catch(Exception e){e.printStackTrace();
                      System.out.println("Exception @ jSlider stateChanged : " + e.getMessage() );
            });Thanks!

    The exception is happening because the ChangeListener thread does not own the monitor on "thr" (see the api documentation for Object.wait). That can be fixed by putting it in a synchronized (this) { ... } block.
    However, I see bigger problems. First, recognize that Java is going to call your ChangeEvent code on the event handling thread, so you definitely don't want it to wait. The screen will stop repainting and the user's mouse release event won't be processed, because you will have suspended the thread that handles those things. Second, you should not modify the position of the slider from any thread other than the event handling thread, for reasons documented at [http://java.sun.com/developer/technicalArticles/Threads/swing/]. That article also shows techniques that are safe.
    I don't mean to be discouraging, just wanted to point out a couple more things so you didn't get strange behavior without knowing why! What you are attempting actually requires some multi-threading skill, so study up!
    Cheers,
    Eric

  • Multi-Client TCP Server /w Swing GUI

    Hi everybody,
    i have to develop a Multi-Client TCP Server with a Swing GUI. The GUI mainly consists of a JTable which shows various trace messages from processes running on other computers. As the data needs to be filtered i�m using a custom TableModel derived from AbstractTableModel. I�m creating a new thread for every client that connects as shown in http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
    Now every client thread reads data from its TCP connection and puts it into the JTable by calling the method addRow of the model. But i�m getting strange NullPointerExceptions and IndexOutOfBoundExceptions when data arrives (i�m using ArrayList in the model). These exceptions never show in a single-threaded Swing app (i�ve tested this already, so i don�t think it�s a bug in my model), so i think this is a problem with Swing�s thread unsafety? Do you have any hints on how to get away with it? Also general design tips for a Multi-Client TCP Server /w Swing GUI are greatly appreciated.
    Thanks in advance!
    Best regards,
    Disposable_Hero

    Of course, but i don�t think it is the model (as said before it works fine in a single thread swing app)
    Here�s the code:
    public class LogTableModel extends AbstractTableModel{
    private Vector dataVector;
    private Vector filterVector;
    private String[] columnIdentifiers;
    private Vector filteredbyProcess;
    private Vector filteredbyLoglevel;
    private boolean bEnableRefresh;
    /** Creates a new instance of LogTableModel */
    public LogTableModel() {
    dataVector=new Vector(0);
    columnIdentifiers=new String[]{"LogTime","HostName","IP","ProcessName","LogLevel","Handle","PID","TID","LogData"};
    filteredbyProcess=new Vector(0);
    filteredbyLoglevel=new Vector(0);
    filterVector=new Vector(0);
    bEnableRefresh=true;
    public synchronized void enableRefresh(boolean bEnableRefresh){
    this.bEnableRefresh=bEnableRefresh;
    if(bEnableRefresh){
    this.buildIndexListBasedOnFilter();
    public synchronized void addRow(LogLine row){
    dataVector.add(row);
    if(bEnableRefresh)
    this.buildIndexListBasedOnFilter();
    public synchronized void addFilter(Filter filter){
    filterVector.add(filter);
    if(filter.isActive())
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterActive(String name,boolean active){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setActive(active);
    if(active)
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterLoglevel(String name,int Loglevel){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setLoglevel(Loglevel);
    if(tmp.isActive()==false)
    this.buildIndexListBasedOnFilter();
    private void buildIndexListBasedOnFilter(){
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    applyProcessFilter();
    applyLoglevelFilter();
    if(bEnableRefresh)
    this.fireTableDataChanged();
    private void applyProcessFilter(){
    LogLine line=null;
    Filter filter=null;
    for(int i=0;i<dataVector.size();i++){
    for(int j=0;j<filterVector.size();j++){
    filter=(Filter)filterVector.elementAt(j);
    line=(LogLine)dataVector.elementAt(i);
    if(filter.isActive()&&(filter.getName().equals(line.getProcessName()))){
    line.setHidden(true);
    break;
    else{
    line.setHidden(false);
    if(line.getHidden()!=true)
    filteredbyProcess.add(new Integer(i));
    private void applyLoglevelFilter(){
    for(int i=0;i<filteredbyProcess.size();i++){
    int index=((Integer)filteredbyProcess.get(i)).intValue();
    LogLine line=(LogLine)dataVector.elementAt(index);
    for(int j=0;j<filterVector.size();j++){
    if(((Filter)filterVector.elementAt(j)).getName().equals(line.getProcessName())){
    Filter filter=(Filter)filterVector.elementAt(j);
    if((filter.getLoglevel()&line.getLogLevelAsInt())!=line.getLogLevelAsInt())
    line.setHidden(true);
    else
    filteredbyLoglevel.add(new Integer(index));
    break;
    public synchronized String getColumnName(int columnIndex){
    return columnIdentifiers[columnIndex];
    public synchronized void clearData(){
    dataVector.clear();
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    public synchronized int getColumnCount() {
    return columnIdentifiers.length;
    public synchronized int getRowCount() {
    return filteredbyLoglevel.size();
    public synchronized Object getValueAt(int rowIndex, int columnIndex) {
    int iIndex=((Integer)filteredbyLoglevel.get(rowIndex)).intValue();// hier krachts warum???
    LogLine tmp=(LogLine)dataVector.elementAt(iIndex);
    switch(columnIndex){
    case 0:
    return tmp.getLogTime();
    case 1:
    return tmp.getHostName();
    case 2:
    return tmp.getIP();
    case 3:
    return tmp.getProcessName();
    case 4:
    return tmp.getLogLevel();
    case 5:
    return tmp.getHandle();
    case 6:
    return tmp.getProcessID();
    case 7:
    return tmp.getThreadID();
    case 8:
    return tmp.getLogData();
    default:
    return null;

  • NEED AN URGENT HELP:( MY THREADS NEVER STOPS IT IS IMPOSSIBLE TOSTOP THEM

    Hello
    I have created threads on my jFrame , when pressing the enter button threads are created and each one of these thread draws a rectangule clears rectangle and draws again by that way I walk waway these rectangules .SO on I want to stop these threads when pushing the reset button .I tried to put a lot of flags on my thread and also directly call the thread.stop(); methods but IT IS IMPOSSIBLE TO STOP OR KILL THESE THREADS, I use Netbeans ..
    I WONDER , THRESE IS ANYTHING THAT I DO NOT KNOW ABOUT ,THREADS ARE NOT KILLED WHEN USING JFRAME OR JAVA THROWS EVENT EVERY MINUTE FOR ENTER BUTTON?
    PLEASE HELP ME I AM GONNA CREAZY ABOUT JAVA,JAVA THREADS,SWING ,JFRAMES......
    :(((((((((((((((((HELP ME

    WRITING LIKE THIS!!!!!! DOES NOT!!!!!! MAKE PEOPLE!!!! WANT TO ANSWER YOUR!!!!! QUESTIONS!!!!!! IN FACT,!!!!!! IT'S RATHER ANNOYING!!!!! TO READ!!!!!! AND VERY!!!! FEW PEOPLE WILL!!!!!! BOTHER TO READ A POST!!!!!! THAT LOOKS LIKE!!!!! THIS!!!!!!!
    To repeat the excellent guidelines from JavaRanch:
    * We all answer questions here voluntarily, in our leisure time. We do that because doing so is fun for us, because we enjoy helping people and having interesting discussions. Guess what? It is much less fun if it gets stressful. So the last thing you want to do to get us to answer your question is to pass your stress over to us.
    * People who are stressed and want a fast answer often don't even find the time to do the necessary research or to formulate their question in an easy to comprehend way. That's even less fun to work with. So you really don't want us to feel your stress. Instead you want to take your time to write a well formulated post that is fun to answer. The less likely it is for us to know that your question is urgent, the more likely you are to get a fast answer!
    * The simple notion that you want your post to be answered faster than those of the other members might feel rather unfair to some of us. Doubly so because often "urgent" questions actually are homework questions. Yours might be different, but someone who had bad experiences with this type of question might not read far enough to notice.
    * If it is really that urgent, my answer may already come too late, so I will think twice before taking the time to formulate it.
    * Last but not least, having the word "urgent" in the subject line actually obfuscates it, makes it harder to decipher what the actual question is, and therefore to decide to actually read the thread. This grossly conflicts with the important practice to UseAMeaningfulSubjectLine.
    ~

  • Rendering fails, but no error message is provided.

    Hello, I'm encountering a very strange behavior of Swing. I have an application (all used components are Swing) using Java3D (but I don't think that would cause my problems).
    The GUI renders fine most of time, but sometimes (almost randomly) some JPanels are not rendered properly - it looks like just eg. their top and left 10% are rendered and then this small piece is repeated over the whole JPanel. I don't even know if it is only the problem of JPanels. This description wouldn't say you much, so I rather provide some screenshots.
    A normal look on the GUI - http://www.ms.mff.cuni.cz/~peckam/share/swing_rendering_error_good.png
    The GUI with the error - http://www.ms.mff.cuni.cz/~peckam/share/swing_rendering_error_bad.png
    I am able to raise this behavior explicitly by throwing an uncaught exception in my swing-handling code.
    What is worse, sometimes it happens without an uncaught exception (but always it is in response to some user action - selecting a value in combobox, pressing a button or so). I've searched all my code for some blocks that could catch an exception and not write it out to the console, but no such place is in my code. So I know my code doesn't throw any uncaught exceptions.
    Maybe the problem could be in a library I use, I don't know.
    I've even tried to add a uncaught exception listener to both Thread and the EDT, but no exception was written out.
    I'm lost in debugging this, so please help me finding some good start points to find the cause of this problem. Thank you all very much.

    Hello,
    Thanks for the info about Java 3D.
    Andrew Thompson wrote:
    Ensure (...) The GUI is updated on the EDT. Thank you for forcing myself into the unpopular work. That was it.Great. Remember it (that's a classic).
    I now execute as much code on EDT as reasonable and I haven't encountered this error since then. But due to its randomness (...)To make things clear, only code that accesses Swing widgets and their models should run on the EDT, but I think that's what you were implying.
    I'm more concerned by your as much as reasonable . If you meant in terms of, the cost it takes to fix all the code, you should estimate it and plan to do it anyway. As you noticed, the effects of incorrect thread management in Swing are unpredictable, and may, and certainly will, appear sooner or later, in a situation that just escaped your testing, or that stems from a specific race condition.
    Since you haven't frowned at Andrew's warning, you're probably aware of that, but if you aren't, you should really take a look at the tutorial about concurrency in Swing (http://download.oracle.com/javase/tutorial/uiswing/concurrency/), to know the reasons, and the recommendations, as to how to write correctly threaded Swing programs.
    I reserve the option to reopen this thread if it shows again some time later. But I hope it is fixed ;)Fix your non-EDT-aware code first :o)
    And just a note about the form, if you come back with a different problem (even though it is likely due to improper threading), open a new topic instead, and reference this one.
    Much luck.
    J.

  • [ANN] Foxtrot 2.0 Released !

    Foxtrot is the simple API for using threads in your Swing applications, fully compatible with Java Web Start.
    Foxtrot uses the synchronous model to make very easy to write threaded Swing code; it's easy to backport your Swing applications to make them snappier and simpler.
    Release 2.0 features an improved API to customize Foxtrot components.
    Enjoy Foxtrot at http://foxtrot.sourceforge.net

    Customer with a valid metalink account can download the patch as follows
    Log into metalink
    Select Patches from the list of options shown on the left hand side of initial welcome screen
    Click the new metalink patch search link
    Enter Patch No 3095277 and click go.
    Select the required OS and click download.
    Follow the installation instructions included with the patch. Do not forget to run the catpatch script after installing the patch.
    Note that this patch includes a new version of the Oracle Univeral Installer. You must upgrade to the version of the OUI included as part of the patch before installing the patch itself.

  • JTextfield  listening for changes from other class

    Hi,
    Assuming I have a Jtextfield in one of the class1 extend Jframe,
    how do I update the jtextfield so that it could up make accessible by other class and continuously updated to reflect the input for value rom another class2.
    In other words very much similar to the observable model view concept
    class 1 may be look like
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setEditable(false);
    class 2 may be look similar to the following
    public void out_1(){
    setStop1("N");
    for (int i=1;i<100;i++){
    class_1.getJTextField1().setText(String.valueOf(i)); // System.out.println(i);
    setOuti(i);
    setStop1("N");

    HI,
    I have attempted with the following coding , test 1 the source display generated using Netbeans GUI , t est2 the worker code ,and mybean the bean , so far nothing seems to work .
    I have not try the threaded swing concept as I am not familar with the concurrency but i am not sure whether propertylistener will do the job or not
    In summary , list of method employed are :
    binding the jtextfield1 to a bean,
    jtextfield add document listener ,
    Coding objective
    1. Test 1 defined jtexfield1 and jbutton
    2 Jbutton added actionlistener , where upon click,
    Execute Test 2 which will assign a series of integer to the bean , own setters & getters, Output is achieved via Test 1 jtextfield1 supposingly to display all the running number from 1 to 99 continuously until the test2 out_1 method finished the execution
    Anyone could provide the assistance .
    Thank
    * Test_1.java
    * Created on July 25, 2007, 9:23 PM
    package sapcopa;
    import java.beans.PropertyChangeListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Document;
    import sapcopa.MyBean.*;
    public class Test_1 extends javax.swing.JFrame {
    /** Creates new form Test_1 */
    // private Test_2 t2=new Test_2();
    private String input_txt;
    public Test_1() {
    myBean1=new MyBean();
    myBean1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
    bean_chg(evt);
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    myBean1 = new sapcopa.MyBean();
    jTextField1 = new javax.swing.JTextField();
    jTextField1.getDocument().addDocumentListener(new MyDocumentListener());
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setEditable(false);
    jTextField1.setText(myBean1.getRecord_Process());
    jTextField1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
    txt1_chg(evt);
    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    But1(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(19, 19, 19)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(jButton1)))
    .addContainerGap(131, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(21, 21, 21)
    .addComponent(jButton1)
    .addContainerGap(216, Short.MAX_VALUE))
    pack();
    }// </editor-fold>//GEN-END:initComponents
    private void txt1_chg(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txt1_chg
    // TODO add your handling code here:
    //myBean1=new MyBean();
    try {
    jTextField1.setText(myBean1.getRecord_Process());
    } catch (Exception e){
    e.printStackTrace();
    }//GEN-LAST:event_txt1_chg
    private void bean_chg(java.beans.PropertyChangeEvent evt){
    jTextField1.setText(myBean1.getRecord_Process());
    private void But1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_But1
    //getJTextField1().getDocument().addDocumentListener(new MyDocumentListener());
    Test_2 t2=new Test_2();
    t2.out_1();
    try{
    System.out.println("Button 1 mybean->"+myBean1.getRecord_Process());
    } catch (Exception e){
    e.printStackTrace();
    // TODO add your handling code here:
    }//GEN-LAST:event_But1
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Test_1().setVisible(true);
    public javax.swing.JTextField getJTextField1() {
    return jTextField1;
    public void setJTextField1(javax.swing.JTextField jTextField1) {
    this.jTextField1 = jTextField1;
    class MyDocumentListener implements DocumentListener {
    final String newline = "\n";
    public void insertUpdate(DocumentEvent e) {
    // updateLog(e, "inserted into");
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void removeUpdate(DocumentEvent e) {
    //updateLog(e, "removed from");
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void changedUpdate(DocumentEvent e) {
    //Plain text components don't fire these events.
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void updateLog(DocumentEvent e, String action) {
    Document doc = (Document)e.getDocument();
    int changeLength = e.getLength();
    // jTextField1.setText(String.valueOf(changeLength));
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public String getInput_txt() {
    return input_txt;
    public void setInput_txt(String input_txt) {
    this.input_txt = input_txt;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    private sapcopa.MyBean myBean1;
    // End of variables declaration//GEN-END:variables
    * Test_2.java
    * Created on July 25, 2007, 9:26 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package sapcopa;
    import sapcopa.MyBean.*;
    public class Test_2 {
    private Test_1 t1=new Test_1();
    private int outi;
    private String stop1;
    MyBean mybean;
    /** Creates a new instance of Test_2 */
    public Test_2() {
    public void out_1(){
    setStop1("N");
    mybean=new MyBean();
    for (int i=1;i<100;i++){
    mybean.setRecord_Process(String.valueOf(i));
    setOuti(i);
    setStop1("N");
    setStop1("Y");
    public int getOuti() {
    return outi;
    public void setOuti(int outi) {
    this.outi = outi;
    public String getStop1() {
    return stop1;
    public void setStop1(String stop1) {
    this.stop1 = stop1;
    * MyBean.java
    * Created on July 24, 2007, 12:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package sapcopa;
    import javax.swing.JTextField;
    public class MyBean {
    /** Creates a new instance of MyBean */
    public MyBean() {
    * Holds value of property record_Process.
    private JTextField txt_rec_process;
    private String record_Process;
    * Utility field used by bound properties.
    private java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this);
    * Adds a PropertyChangeListener to the listener list.
    * @param l The listener to add.
    public void addPropertyChangeListener(java.beans.PropertyChangeListener l) {
    propertyChangeSupport.addPropertyChangeListener(l);
    * Removes a PropertyChangeListener from the listener list.
    * @param l The listener to remove.
    public void removePropertyChangeListener(java.beans.PropertyChangeListener l) {
    propertyChangeSupport.removePropertyChangeListener(l);
    * Getter for property record_Process.
    * @return Value of property record_Process.
    public String getRecord_Process() {
    return this.record_Process;
    * Setter for property record_Process.
    * @param record_Process New value of property record_Process.
    public void setRecord_Process(String record_Process) {
    String oldRecord_Process = this.record_Process;
    this.record_Process = record_Process;
    propertyChangeSupport.firePropertyChange("record_Process", oldRecord_Process, record_Process);
    * Holds value of property rec_Match.
    private String rec_Match;
    * Getter for property rec_Match.
    * @return Value of property rec_Match.
    public String getRec_Match() {
    return this.rec_Match;
    * Setter for property rec_Match.
    * @param rec_Match New value of property rec_Match.
    public void setRec_Match(String rec_Match) {
    String oldRec_Match = this.rec_Match;
    this.rec_Match = rec_Match;
    propertyChangeSupport.firePropertyChange("rec_Match", oldRec_Match, rec_Match);
    public JTextField getTxt_rec_process() {
    return txt_rec_process;
    public void setTxt_rec_process(JTextField txt_rec_process) {
    JTextField oldTxt_rec_process=this.txt_rec_process;
    this.txt_rec_process = txt_rec_process;
    propertyChangeSupport.firePropertyChange("txt_rec_process", oldTxt_rec_process, txt_rec_process);
    }

  • NullPointerException in BasicTableHeaderUI

    Hi,
    I am populating an JTable with some information. everything works fine but while populating table am getting following exception(still am able to populate table correctly)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTableHeaderUI.paintCell(BasicTableHeaderUI.java:394)
    Functionality wise it won't affect my application but my GUI gets freezing because of this exception. This exception is in api itself so i didn't find any way to handle it in my code itself. I do get the same exception when i try to sort the coloumn by mouse click on coloumn header.
    I am doing all the lenghty operations(row creation) in background thread(swing worker thread).
    my java platform is -
    java version "1.6.0_01"
    Java(TM) SE Runtime Environment (build 1.6.0_01-b06)
    Java HotSpot(TM) Client VM (build 1.6.0_01-b06, mixed mode, sharing)
    Can somebody guide me about how to rectify/handle this exception.
    thanks in advance!
    Sachin!!!

    Thnx for respond!!! Here is the stack trace-
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler.mouseClicked(BasicTableHeaderUI.java:86)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
    at java.awt.Component.processMouseEvent(Component.java:6041)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3995)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Maybe you are looking for

  • Bonjour for Windows no longer works after SP3 is installed

    Bonjour for Windows was working fine until SP3 came out. Now I can see the printer and Bonjour goes through the motions to set it up, but I can't print to the printer. The whole construct of "Printer.local" or "AirPortExpress.local" doesn't seem to w

  • External hard drive icons(fire wire)

    I have a lacie external drive hooked up to my G5.I went into disk utility,and when i clicked on the lacie it had a beautiful fire wire icon in orange.All of the icons that came with the lacie are ugly.I checked the lacie website for the icon and it w

  • Export PSD file / open in Photoshop elements?

    I have created a folder of image files in Photoshop CS4 that I would like to share with a friend. I have a Mac, and the friend has a PC with Photoshop Elements. Can the native PSD files be opened in Elements? thanks

  • SSIS - Sharepoint excel as datasource

    Hi ! Is there anyway to have excel located in sharepoint server to be used as datasource in SSIS? Regards,

  • Multiple canvas navigation help

    Hi all I'm developing a form with multiple canvases like A,B,C and D I'm able to navigate to the canvases successfully during run time by having some go_item code B-->D-->C-->A i don't want to navigate like this my need is if I close any the canvas B