Solved

multithread swing

Posted on 2000-02-15
4
449 Views
Last Modified: 2013-11-23
Hi all, I have a problem with swing multithread I need
show a dialog with a progress bar, and two buttons one is to ok and the other is to cancel operation , I had tried Progress monitor
but that don´t work, and create a dialog with a progress bar
and try do a dialog implement Runnable and create a thread to
update interface, I put a thread into dialog to update Graphics.

the problem is:
I create a dialog and call the show method, the frame e show
but the graphical bean don't be showed, after I start a loop
I had put some println to see for's counter and every except
graphical interface, and it don´t update the graphical interface and
don´t hold events, I guess it hold all events and put at queue
and just process after finish the loop. When the loop finish a progress
bar is showed and all works.

p.s sorry by my inglish
[]´s MDMSantos.
0
Comment
Question by:marcioSantos
  • 2
  • 2
4 Comments
 
LVL 8

Expert Comment

by:diakov
ID: 2523412
With the solution I suggest your dialog can even be modal.

The solution is the following:

1. Do not do the processing in the event thread. To solve this create and start a thread, after that the event handler should return.

2. Now the porblem is how to update the dialog from the processing thread. You do that by calling SwingUtilities.invokeLater(runnable_obj). What it does is it posts a very special event in the event queue of swing and returns immediately.

3. The special event contains a reference to the runnable_obj and when its turn to be processed comes, the swing calls the run() method on the runnable_obj in the event thread.

4. What you have to do to use this scheme for your purposes is, to implement Rnnable in one of your objects. Its run() will be the updater  of the progress bar. The update value can be set with a synhronized method, so you fisrt set it within the processsing thread, then call invokeLater(), then in the run() of the updater you retrieve and repaint() your progress bar.

Tell me if you need more help.

Cheers,
  Nikolay
0
 

Author Comment

by:marcioSantos
ID: 2526577
Sorry, I forgot to tell that I had try
swingUtilities but don´t work, below goes the source
code. they are two class one called "Dialogo" and other is called "Frame". when I press the jbutton1
the dialog is created, and when I press the jbutton2
the loop is executed and call the method incrementa of Dialogo Class and it try update window
but this don´t work.
Very thanks diakov but this don´t work.
[]´s MDMSantos.


/* source code init */
package tswing;

/**
 * Insert the type's description here.
 * Creation date: (16/02/00 08:44:25)
 * @author: Administrator
 */
import javax.swing.*;
public class Dialogo extends javax.swing.JDialog {

      private boolean cancela=false;
      private javax.swing.DefaultBoundedRangeModel modelo=null;
      private int contador;
class IvjEventHandler implements java.awt.event.ActionListener {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                  if (e.getSource() == Dialogo.this.getJButton1())
                        connEtoC1();
                  if (e.getSource() == Dialogo.this.getJButton2())
                        connEtoC2();
            };
      };
      IvjEventHandler ivjEventHandler = new IvjEventHandler();
      private javax.swing.JButton ivjJButton1 = null;
      private javax.swing.JButton ivjJButton2 = null;
      private javax.swing.JPanel ivjJDialogContentPane = null;
      private javax.swing.JProgressBar ivjJProgressBar1 = null;
/**
 * Dialogo constructor comment.
 */
public Dialogo() {
      super();
      initialize();
      modelo= new DefaultBoundedRangeModel(0,1,0,100);
      getJProgressBar1().setModel(modelo);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Dialog
 */
public Dialogo(java.awt.Dialog owner) {
      super(owner);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Dialog
 * @param title java.lang.String
 */
public Dialogo(java.awt.Dialog owner, String title) {
      super(owner, title);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Dialog
 * @param title java.lang.String
 * @param modal boolean
 */
public Dialogo(java.awt.Dialog owner, String title, boolean modal) {
      super(owner, title, modal);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Dialog
 * @param modal boolean
 */
public Dialogo(java.awt.Dialog owner, boolean modal) {
      super(owner, modal);
      modelo= new DefaultBoundedRangeModel(0,1,0,100);
      getJProgressBar1().setModel(modelo);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Frame
 */
public Dialogo(java.awt.Frame owner) {
      super(owner);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Frame
 * @param title java.lang.String
 */
public Dialogo(java.awt.Frame owner, String title) {
      super(owner, title);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Frame
 * @param title java.lang.String
 * @param modal boolean
 */
public Dialogo(java.awt.Frame owner, String title, boolean modal) {
      super(owner, title, modal);
}
/**
 * Dialogo constructor comment.
 * @param owner java.awt.Frame
 * @param modal boolean
 */
public Dialogo(java.awt.Frame owner, boolean modal) {
      super(owner, modal);
}
/**
 * connEtoC1:  (JButton1.action. --> Dialogo.jButton1_ActionEvents()V)
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC1() {
      try {
            // user code begin {1}
            // user code end
            this.jButton1_ActionEvents();
            // user code begin {2}
            // user code end
      } catch (java.lang.Throwable ivjExc) {
            // user code begin {3}
            // user code end
            handleException(ivjExc);
      }
}
/**
 * connEtoC2:  (JButton2.action. --> Dialogo.jButton2_ActionEvents()V)
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC2() {
      try {
            // user code begin {1}
            // user code end
            this.jButton2_ActionEvents();
            // user code begin {2}
            // user code end
      } catch (java.lang.Throwable ivjExc) {
            // user code begin {3}
            // user code end
            handleException(ivjExc);
      }
}
/**
 * Return the JButton1 property value.
 * @return javax.swing.JButton
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JButton getJButton1() {
      if (ivjJButton1 == null) {
            try {
                  ivjJButton1 = new javax.swing.JButton();
                  ivjJButton1.setName("JButton1");
                  ivjJButton1.setText("JButton1");
                  ivjJButton1.setBounds(241, 195, 85, 27);
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJButton1;
}
/**
 * Return the JButton2 property value.
 * @return javax.swing.JButton
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JButton getJButton2() {
      if (ivjJButton2 == null) {
            try {
                  ivjJButton2 = new javax.swing.JButton();
                  ivjJButton2.setName("JButton2");
                  ivjJButton2.setText("JButton2");
                  ivjJButton2.setBounds(140, 195, 85, 27);
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJButton2;
}
/**
 * Return the JDialogContentPane property value.
 * @return javax.swing.JPanel
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JPanel getJDialogContentPane() {
      if (ivjJDialogContentPane == null) {
            try {
                  ivjJDialogContentPane = new javax.swing.JPanel();
                  ivjJDialogContentPane.setName("JDialogContentPane");
                  ivjJDialogContentPane.setLayout(null);
                  getJDialogContentPane().add(getJProgressBar1(), getJProgressBar1().getName());
                  getJDialogContentPane().add(getJButton1(), getJButton1().getName());
                  getJDialogContentPane().add(getJButton2(), getJButton2().getName());
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJDialogContentPane;
}
/**
 * Return the JProgressBar1 property value.
 * @return javax.swing.JProgressBar
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JProgressBar getJProgressBar1() {
      if (ivjJProgressBar1 == null) {
            try {
                  ivjJProgressBar1 = new javax.swing.JProgressBar();
                  ivjJProgressBar1.setName("JProgressBar1");
                  ivjJProgressBar1.setBounds(101, 94, 148, 14);
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJProgressBar1;
}
/**
 * Called whenever the part throws an exception.
 * @param exception java.lang.Throwable
 */
private void handleException(java.lang.Throwable exception) {

      /* Uncomment the following lines to print uncaught exceptions to stdout */
      // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
      // exception.printStackTrace(System.out);
}
/**
 * Insert the method's description here.
 * Creation date: (10/02/00 17:32:34)
 */
public void incrementa(){
            try{
            Thread.sleep(10);
      } catch(InterruptedException e){}

      Runnable runme = new Runnable() {
                        public void run() {
                        System.out.println("the value is :"+contador+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                          modelo.setValue(contador);
                         getJProgressBar1().invalidate();
                           getJProgressBar1().repaint();
                        }
      };
      this.invalidate();
      this.repaint();
      SwingUtilities.invokeLater(runme);
      contador++;
      if (  modelo.getValue()>=modelo.getMaximum()-1 ) {
            getJButton1().setEnabled(true);
      }
      
            
}
/**
 * Initializes connections
 * @exception java.lang.Exception The exception description.
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
      // user code begin {1}
      // user code end
      getJButton1().addActionListener(ivjEventHandler);
      getJButton2().addActionListener(ivjEventHandler);
}
/**
 * Initialize the class.
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
      try {
            // user code begin {1}
            // user code end
            setName("Dialogo");
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setSize(426, 240);
            setContentPane(getJDialogContentPane());
            initConnections();
      } catch (java.lang.Throwable ivjExc) {
            handleException(ivjExc);
      }
      // user code begin {2}
      // user code end
}
/**
 * Comment
 */
public void jButton1_ActionEvents() {
      cancela=true;
      return;
}
/**
 * Comment
 */
public void jButton2_ActionEvents() {
      return;
}
/**
 * Starts the application.
 * @param args an array of command-line arguments
 */
public static void main(java.lang.String[] args) {
      // Insert code to start the application here.
      Dialogo dia= new Dialogo();
      dia.show();
      for (int f=0;f<=100;f++){
            dia.incrementa();
      }
}
}











/******************* Other Class *********************/
 













package tswing;

/**
 * Insert the type's description here.
 * Creation date: (16/02/00 08:43:33)
 * @author: Administrator
 */
public class Frame extends javax.swing.JFrame {
      IvjEventHandler ivjEventHandler = new IvjEventHandler();
      private javax.swing.JButton ivjJButton1 = null;
      private javax.swing.JPanel ivjJFrameContentPane = null;
      private Dialogo dia=null;

class IvjEventHandler implements java.awt.event.ActionListener {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                  if (e.getSource() == Frame.this.getJButton1())
                        connEtoC1();
                  if (e.getSource() == Frame.this.getJButton2())
                        connEtoC2();
            };
      };
      private javax.swing.JButton ivjJButton2 = null;
/**
 * Frame constructor comment.
 */
public Frame() {
      super();
      initialize();
}
/**
 * Frame constructor comment.
 * @param title java.lang.String
 */
public Frame(String title) {
      super(title);
}
/**
 * connEtoC1:  (JButton1.action. --> Frame.jButton1_ActionEvents()V)
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC1() {
      try {
            // user code begin {1}
            // user code end
            this.jButton1_ActionEvents();
            // user code begin {2}
            // user code end
      } catch (java.lang.Throwable ivjExc) {
            // user code begin {3}
            // user code end
            handleException(ivjExc);
      }
}
/**
 * connEtoC2:  (JButton2.action. --> Frame.jButton2_ActionEvents()V)
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC2() {
      try {
            // user code begin {1}
            // user code end
            this.jButton2_ActionEvents();
            // user code begin {2}
            // user code end
      } catch (java.lang.Throwable ivjExc) {
            // user code begin {3}
            // user code end
            handleException(ivjExc);
      }
}
/**
 * Return the JButton1 property value.
 * @return javax.swing.JButton
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JButton getJButton1() {
      if (ivjJButton1 == null) {
            try {
                  ivjJButton1 = new javax.swing.JButton();
                  ivjJButton1.setName("JButton1");
                  ivjJButton1.setText("JButton1");
                  ivjJButton1.setBounds(234, 159, 85, 27);
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJButton1;
}
/**
 * Return the JButton2 property value.
 * @return javax.swing.JButton
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JButton getJButton2() {
      if (ivjJButton2 == null) {
            try {
                  ivjJButton2 = new javax.swing.JButton();
                  ivjJButton2.setName("JButton2");
                  ivjJButton2.setText("JButton2");
                  ivjJButton2.setBounds(88, 151, 85, 27);
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJButton2;
}
/**
 * Return the JFrameContentPane property value.
 * @return javax.swing.JPanel
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JPanel getJFrameContentPane() {
      if (ivjJFrameContentPane == null) {
            try {
                  ivjJFrameContentPane = new javax.swing.JPanel();
                  ivjJFrameContentPane.setName("JFrameContentPane");
                  ivjJFrameContentPane.setLayout(null);
                  getJFrameContentPane().add(getJButton1(), getJButton1().getName());
                  getJFrameContentPane().add(getJButton2(), getJButton2().getName());
                  // user code begin {1}
                  // user code end
            } catch (java.lang.Throwable ivjExc) {
                  // user code begin {2}
                  // user code end
                  handleException(ivjExc);
            }
      }
      return ivjJFrameContentPane;
}
/**
 * Called whenever the part throws an exception.
 * @param exception java.lang.Throwable
 */
private void handleException(java.lang.Throwable exception) {

      /* Uncomment the following lines to print uncaught exceptions to stdout */
      // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
      // exception.printStackTrace(System.out);
}
/**
 * Initializes connections
 * @exception java.lang.Exception The exception description.
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
      // user code begin {1}
      // user code end
      getJButton1().addActionListener(ivjEventHandler);
      getJButton2().addActionListener(ivjEventHandler);
}
/**
 * Initialize the class.
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
      try {
            // user code begin {1}
            // user code end
            setName("Frame");
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setSize(426, 240);
            setContentPane(getJFrameContentPane());
            initConnections();
      } catch (java.lang.Throwable ivjExc) {
            handleException(ivjExc);
      }
      // user code begin {2}
      // user code end
}
/**
 * Comment
 */
public void jButton1_ActionEvents() {
       dia= new Dialogo();
      dia.show();
      
      return;
}
/**
 * Comment
 */
public void jButton2_ActionEvents() {
      for (int f=0;f<=100;f++){
            dia.incrementa();
      }
      return;
}
/**
 * Starts the application.
 * @param args an array of command-line arguments
 */
public static void main(java.lang.String[] args) {
      // Insert code to start the application here.
      Frame fr= new Frame();
      fr.show();
}
}

0
 
LVL 8

Accepted Solution

by:
diakov earned 100 total points
ID: 2526672
It is difficult to read this source code with all the proprietary tags of Visual Age. I would suggest a clean example.

An application that shows a JFrame with one button, that upon a click opens a modal dialog and starts a thread that does calculation (incremento). This thread will use the example I provided to update the progress dialog.


This example works fine.

If you follow its architecture you will be able to accomplish your goal.

Cheers,
  Nik

//-------------------------
//main java class
package progress;

import javax.swing.UIManager;

public class Test
{
  boolean packFrame = false;

  //Construct the application
  public Test()
  {
    MainFrame frame = new MainFrame();
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame)
      frame.pack();
    else
      frame.validate();
    frame.setVisible(true);
  }

  //Main method
  public static void main(String[] args)
  {
    try
    {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e)
    {
    }
    new Test();
  }
}

//-------------------------
//main frame java file
package progress;

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

public class MainFrame extends JFrame
{
  JButton starter = new JButton();
  FlowLayout flowLayout1 = new FlowLayout();

  //Construct the frame
  public MainFrame()
  {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try
    {
      jbInit();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }

  //Component initialization
  private void jbInit() throws Exception
  {
    starter.setText("Starter");
    starter.addActionListener(new java.awt.event.ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        starter_actionPerformed(e);
      }
    });
    this.getContentPane().setLayout(flowLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Test");
    this.getContentPane().add(starter, null);
  }

  //Overridden so we can exit on System Close
  protected void processWindowEvent(WindowEvent e)
  {
    super.processWindowEvent(e);
    if(e.getID() == WindowEvent.WINDOW_CLOSING)
    {
      System.exit(0);
    }
  }

  void starter_actionPerformed(ActionEvent e)
  {

    //here open the progress dialog
    ProgressDlg pd = new ProgressDlg(this, "Progress dialog", true);

    //here start the data thread
    CalcThread ct = new CalcThread(pd);
    ct.start();

    pd.setVisible(true);
  }
}
class CalcThread extends Thread
{
  private ProgressDlg dlg = null;
  private int counter = 0;
  CalcThread(ProgressDlg pd)
  {
    dlg = pd;
  }
  public void run()
  {
    //here do the job
    while (dlg.get_flag())
    {
      try
      {
        dlg.set_value("" + counter++);
        Thread.currentThread().sleep(1000);
      }
      catch (Exception e)
      {

      }
      finally
      {

      }
    }
    dlg.dispose();
  }
}
//---------------------
//progress dialog file
package progress;

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

public class ProgressDlg extends JDialog implements Runnable
{
  JPanel panel1 = new JPanel();
  JButton stop = new JButton();
  FlowLayout flowLayout1 = new FlowLayout();
  JLabel progress_item = new JLabel();

  private boolean stop_flag = true;
  private String new_text = "!!!";
  public synchronized void set_flag(boolean b)
  {
    stop_flag = b;
  }
  public synchronized boolean get_flag()
  {
    return stop_flag;
  }
  public synchronized void set_value(String s)
  {
    new_text = s;
    SwingUtilities.invokeLater(this);
  }
  public synchronized String get_value()
  {
    return new_text;
  }

  public ProgressDlg(Frame frame, String title, boolean modal)
  {
    super(frame, title, modal);
    try
    {
      jbInit();
      pack();
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }

  public ProgressDlg()
  {
    this(null, "", false);
  }

  void jbInit() throws Exception
  {
    panel1.setLayout(flowLayout1);
    stop.setText("Stop");
    stop.addActionListener(new java.awt.event.ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        stop_actionPerformed(e);
      }
    });
    progress_item.setText(new_text);
    getContentPane().add(panel1);
    panel1.add(stop, null);
    panel1.add(progress_item, null);
  }
  public void run()
  {
    progress_item.setText(new_text);
    progress_item.repaint();
  }

  void stop_actionPerformed(ActionEvent e)
  {
    set_flag(false);
  }
}

0
 

Author Comment

by:marcioSantos
ID: 2526754
Thank you very much.
this is very helpful
[]'s MDMSantos
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now