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);

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

    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

  • 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

  • Best thread/tutorial on sync?

    I'm just getting started on using an iPad and iTunes.  The official support and most threads are confusing in that I can't seem to find out exactly what happens when you "sync."  I think of the term "sync" as synchronizing, as in making two things completely consistent, without removing anything from either, but this does not seem to be what is happening  in an iPod/iPad "sync" - there is always the possibility of wiping something out! 
    I think use of the term "transfer" would help - instead of saying "sync the iPad to iTunes" or "sync iTunes to the iPad", I would like to see "If you check this checkbox and click APPLY, then X will be transferred from the iPad to the computer and all X in iTunes on the computer will be overwritten.  On the other hand, if you want to add X from the iPad to X on the computer, then do this."
    Any suggestions for a simple unambiguous discussion?

    Download this and do a search for "sync."
    There have been some problems accessing pages on the Apple web site.  If the hyperlink gives you a "We're sorry" message, try again.

  • 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.
    ~

  • Jdbc and multiple thread

    hi, i have an application that creates multiple thread..each thread (querythread) is accessing a webservice(querydb) that retrieves data from different databases. This webservice supposed to create a jdbc connection each time it is invoke by the querythread. The problem is i get an error that a particular table does not exist in the server..This is cause by the confusion in my program..
    The table is access in the wrong server..e.g.(cdsisis.TblHoldings does not exist) this is because thread is confuse and using a different connection..when i tried to use the querydb webservice directly per database it is ok. but when i try to make multiple thread to invoke querydb accessing different database it has this error: cdsisis.TblHoldings does not exist
    cdsisis is a database server..and tblHoldings is a table in another database named silms. i think the thread tends to share resources.
    should it be that thread supposed to be independent with each other? how come this is happening?

    hi, i have an application that creates multiple
    thread..each thread (querythread) is accessing a
    webservice(querydb) that retrieves data from
    different databases. This webservice supposed to
    create a jdbc connection each time it is invoke by
    the querythread. The problem is i get an error that a
    particular table does not exist in the server..This
    is cause by the confusion in my program..
    The table is access in the wrong
    server..e.g.(cdsisis.TblHoldings does not exist) this
    is because thread is confuse and using a different
    connection..when i tried to use the querydb
    webservice directly per database it is ok. but when i
    try to make multiple thread to invoke querydb
    accessing different database it has this error:
    cdsisis.TblHoldings does not exist
    cdsisis is a database server..and tblHoldings is a
    table in another database named silms. i think the
    thread tends to share resources.
    should it be that thread supposed to be independent
    with each other? how come this is happening?I think you should lock your thread while trying to make request or making your connection. When you lock your thread, the currently used variable can not be accessed by another thread. Actually I know you are creating different treads and create different instances of connection. But some how some methods are not thread safe, it means they are static or use static variables. So they change from another thread, while you are trying to access it.
    If lock does not work try this,
    synchronized(this){
    //do your stuff
    }

  • 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.

  • Unable to open documents in pages for iPad

    I use iWork for work on a regular basis. All my documents are organized in folders. Some of my documents show inside their respective folders but I'm unable to open them. For example in one folder I have 12 documents raging from January thru December and I can see all of them, but when I click on December to open it doesn't do anything. Clicking on edit doesnt let me highlight it either. I can't delete it or open it. When logging in to iCloud the documents dont even show on there. Fortunetly I can recreate the damaged documents but I can't get rid of them. Anyone having the same issue who has successfully deleted these? Thanks

    Hi Ankit,
    Thank you for your advice, but Im still having problems.
    Back to the OP.  To avoid the threads getting confused, I suggest the other user starts a new one?
    I have tried ensuring that PDFs are automatically opened by Adobe.  I used the path you suggested.  However, I'm still having the same problem.
    When I went to do this, Adobe was listed in the "recommended" list of products with which to open PDF files.  However, I ignored this and followed your guidance.  Once I had done, nothing happened (i.e. Adobe icon was not added to the 'Other products' list below the 'Recommended').
    To me, this speaks of either a bad installation or bad association in which something is causing Adobe not to recognise itself.
    What else can you advise?
    Is there, for instance, a way to have a clean removal of Adobe, and then reinstall?  I don't even know if this will work. 

Maybe you are looking for

  • Iphone 4s wont power on and is charged

    iphone 4s will not power on and is charged

  • HP Officejet All-in-one Automatic Document Feeder (ADF) Roller

    I have a problem which I believe is mechanical.  The roller on the ADF will not descend to the pressure plate when I try to copy or fax from the ADF.  I talked to the online chat people and they kept trying to get me to remove the faceplate and clean

  • Loop keeping second animation on hold

    hello every one i have an animation loop which triggers another animation. The problem is the loop is on hold while the animation it triggered is completed. I wish some one could give me some examples on how loops could trigger other animations. Swap

  • My iPhone 6 always turn off & goes in recovery mode

    Last week my iPhone 6 started to just shut off by its self. It connected it with iTunes and it said the phone is in recovery mode. I held the power button and home screen button and it turned back on. Since then my iPhone 6 always keeps doing it. I r

  • Import Function in Elements11 is deleting RAW Originals

    Since I recently purchased a camera that the manufactor released after I aquired Elements11, I downloaded the update for thr RAW converter. A problem has occurred.  Eventhough I clicked the box in the Photo Downloader that says "After copying, do not