Making a GUI freeze voluntarily

Hi all,
I use JOptionPane.showConfirmDialog(...) in my actionPerformed method in my class. After clicking the Yes button, a long non GUI operation takes place. Until the long non GUI operation completes its execution, the place where the showConfirmDialog was there is filled by gray background until the non GUI operation completes its execution.
I used invokeLater() and also tried by creating separate THREAD. But what happens in my application is that there is one more message box say "Trade Submitted" is displayed even before the trade is submitted in the non GUI operation. Moreover, using thread requires lot of code changes. So usage of thread is restricted in my application.
Is there any way of freezing the GUI(i.e., after clicking Yes button, my GUI should be there as such but the non GUI operation should start after clicking the Yes button). Once the non GUI operation completes its execution, I should return to the GUI operation(In our case "Trade Submitted"). Can you please help me on this issue.
(NB: In my application, there are menus, which when clicked keeps the menu as such in the frame but starts the non GUI operation. I went through the code there, but there was no code logic there - to make the menu reside as such)

Moreover, using thread requires lot of code changes. So usage of thread is restricted in my application.So, its better to desing to application correctly. If that means rewritting code then thats what you have to do.
A modal dialog will block execution of the code until the dialog is closed. JOptionPane uses modal dialogs so it shouldn't be a problem.

Similar Messages

  • Gui freezes after pressing execute

    hi,
    my program which is done in Swing sort of freezes as soon as press execute until the calling method is finished.
    here is the situation.
    the jFrame contains 2 buttons ( ok & cancel )
    when the ok button is pressed it creates an object & invokes a method in it
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
    var = new Var(patameter list..);
    var.go();this method take some time ( say roughly about 1 min... ) so as soon as I press ok my GUI freezes until that go() method completes.
    this is very annoying, coz I have this new jFrame I need to pop up as soon as OK is pressed so it can show the progress of that go() method. This new window wont even show up sometimes until go() is finished.
    How do I overcome this...
    p.s - I read this thread http://forum.java.sun.com/thread.jspa?threadID=5189368&tstart=0
    But it was a bit confusing to me..
    if you experts can help me out, that would be great. :)
    Cheers

    p.s - I read this thread http://forum.java.sun.com/thread.jspa?threadID=5189368&tstart=0
    Not related to your problem.
    if you experts can help me out, that would be great. :)The Swing experts are found in the Swing forum, where this question is asked and answered all the time.
    You need to use a separate Thread for you long running task so it doesn't block the GUI thread from responding to events.

  • GUI Freezes once socket server is started

    Here's my problem and I am stumped. I have an application which starts a
    socket server and waits for clients to connect. Once connected, the
    server queries XML to the client for display.
    My problem is when I start the server my GUI freezes. I have a simple
    GUI with a start and stop button made in JBuilder. Although the server is running fine and the application works (I can connect and query with my client) the GUI freezes and I have to CTRALTDEL to close the app.
    The method below (see after message) is in the main Application.java class and my GUI is being created in the Frame1.java class. The Frame class has a listener for the button press which calls startServer in
    Application. This was developed in JBuilder Personal edition.
    I keep reading about InvokeLater but not sure if this is what I need. I feel like what is happening is the server starts and the app listens for clients and ignores the GUI.
    Any suggestions would be helpful as madness is setting in.
    Thnaks.
    public static void startServer() {
    try{
    int intPort=9999;
    ServerSocket server = new ServerSocket(intPort);
    System.out.println("Server started...waiting for clients.");
    while(true){
    Socket objSocket = server.accept();
    SocketClient client = new SocketClient(objSocket);
    client.start();
    catch(IOException ioe){
    //dump error
    Here is how the server is being started:
    void button1_actionPerformed(ActionEvent e) {
    try{
    startserver.main(); //make call to start the server
    label2.setText("Running");
    catch (Exception ie) {
    System.err.println("Could not listen on port: 9999.");
    System.exit(-1);
    }

    Swing executes all GUI related code (event handling, painting, etc.) in the so-called event dispatching thread. If you call a blocking method like ServerSocket.accept in this thread, it is blocked and unable to perform further gui tasks.
    public class MyServerThread extends Thread
        private ServerSocket serversocket;
        public void run()
            try
                this.sserversocket = new ServerSocket(9999);
                while(!Thread.interrupted())
                    Socket socket = serversocket.accept();
                    new SocketClient(socket).start();
            catch(IOException ex)
                ex.printStacktract();
        public void shutdown()
            if(this.serversocket != null)
                //closing the socket will cause accept() to throw an exception and therefor quit its loop
                try { this.serversocket.close(); } catch(IOException ignored) {}
                this.interrupt();
                this.serversocket = null;
    //in your GUI class
    private MyServerThread serverthread;
    void startserver()
        serverthread = new MyServerThread();
        serverthread.start();
    void stopserver()
        serverthread.shutdown();
        serverthread = null;
    }

  • GUI Freezes

    I want the hex code of a file to be generated on button press from GUI. Right now, the code works fine for small files but for large files, the GUI freezes.
    class SW extends SwingWorker<String,Void>{
         File finsw;
         public String doInBackground() throws Exception
         String hex="";
         String hex2="";
         finsw=new File(jt.getText());
         BufferedInputStream in = new BufferedInputStream(new FileInputStream(finsw));
         int b,i=0,c=0;
         int count=0;
         while ((b = in.read()) != -1)
         { c++;
         try { hex=Integer.toHexString(b);
         hex2=hex2+hex;
         } catch(Exception e){System.out.println("Example5.java"+e);}
         if (hex.length() == 1)
         hex = '0' + hex;} //end of func
         in.close();
         return hex2;
                             //String kfrmsw=Example5.displayBinaryFile2(finsw);
                             //return kfrmsw;
    }// end of doInBackground
    protected void done()
    { try { String m=get();
    System.out.println(m);}catch(Exception e) {System.out.println(e);}}
    }//end of class SW
    This is the main function
    public static void main(String args[])
         //new gui();
         SwingUtilities.invokeLater(new Runnable() {public void run() {new gui();}});
         JFrame frame = new JFrame("VRDS");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.add(new gui());
         frame.pack();
    frame.setVisible(true);
    }//end of main
    This is the EDT
    public void actionPerformed(ActionEvent e) {
    SW worker=new SW();
    if (e.getSource() == jb)//the scan button
    // read file to be scanned
         String k="";
         final File f=new File(jt.getText());                  
         try {
              worker.execute();
              System.out.println("Worker.get="+worker.get());
    } catch(Exception re) { System.out.println("Exception from read file to be scanned"+re); }            

    class SW extends SwingWorker<String,Void>{
         File finsw;
         public String doInBackground() throws Exception
         String hex="";
         String hex2="";
         finsw=new File(jt.getText());
         BufferedInputStream in = new BufferedInputStream(new FileInputStream(finsw));
         int b,i=0,c=0;
         int count=0;
         while ((b = in.read()) != -1)
         { c++;
         try { hex=Integer.toHexString(b);
         hex2=hex2+hex;
         } catch(Exception e){System.out.println("Example5.java"+e);}
         if (hex.length() == 1)
         hex = '0' + hex;} //end of func
         in.close();
         return hex2;
                             //String kfrmsw=Example5.displayBinaryFile2(finsw);
                             //return kfrmsw;
    }// end of doInBackground
    protected void done()
    { try {
    String m=worker.get();
    System.out.println("M:"+m);
    }catch(Exception e) {System.out.println(e);}
    }//end of class SWThis is the main method
    public static void main(String args[])
         //new gui();
         SwingUtilities.invokeLater(new Runnable() {public void run() {
    //new gui();
         JFrame frame = new JFrame("VRDS");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.add(new gui());
         frame.pack();
            frame.setVisible(true);
    }//end of mainThis is the actionperformed method
    public void actionPerformed(ActionEvent e) {
    //Coding for Scan Button goes here
         if (e.getSource() == jb)
    // read file to be scanned
         String k="";
         final File f=new File(jt.getText());                  
         try {
              worker.execute();
              } catch(Exception re) { System.out.println("Exception from read file to be scanned"+re); }            I want the hex code of file selected from the GUI. For large files, still no output is produced. Also, after generating hex code for 1st file, no hex code is being generated for the second file.

  • My GUI freezes

    Hey, I'm writing a small client/server application and I'm getting a problem, when I start the server the GUI freezes and I haven't been able to solve the problem. Any help will be much appreciated.
    I use 2 classes, Server which handles the serversocket and its connections, and serverInterface which handles the server's GUI.
    Here is the code for the server class:
    public class Server extends JFrame {
         private serverInterface interfaz=null;
         public int fileCant = 0;
         static boolean listening = true;
         private String[][] listFiles = null;
         private int ifiles=0;
         public Server(){
              this.interfaz = new serverInterface(this);          
         public void buttonPressed (int button){
              switch(button){
                case 0: {  try{startServer();}
                           catch(IOException e){System.err.println("Could not listen on port: 7777.");}
                           break;
                         } //se presiono el boton de start
                case 1: {stopServer(); break;} // se presiono el boton de stop
         private void startServer() throws IOException{
              ServerSocket serverSocket = null;
              listFiles = new String[1000][4];
            try {
                 updateVal(1,"0","0",0);
                serverSocket = new ServerSocket(7777);           
            } catch (IOException e) {
                System.err.println("Could not listen on port: 7777.");
                //System.exit(1);
            while(listening){
                 new multiServer(serverSocket.accept(),this).start();
         private void stopServer(){          
              System.exit(-1);
         private void updateVal(int variableUpdate,String ip, String port, int numFiles){
              this.interfaz.updateVal(variableUpdate,ip,port,numFiles);          
         public static void main(String[] args){
                   new Server();
         public void addFiles(Object object, String IP, String Port){
              Vector test = (Vector) object;
              for (int i=0;i<test.size();i++){
                   listFiles[ifiles][0]=(String)test.elementAt(i);
                   listFiles[ifiles][1]= IP;
                   listFiles[ifiles][2]=Port;
                   listFiles[ifiles][3]="online";
                   ifiles++;               
         public void removeFiles(String IP, String Port){
              for (int i =0;i<ifiles;i++){
                   if((IP.equals(listFiles[1]))&&(Port.equals(listFiles[i][2]))){
                        listFiles[i][3] = "offline";
         public DefaultTableModel searchFile(String file){
              DefaultTableModel model = new DefaultTableModel();
              model.addColumn("File");
              model.addColumn("IP Address");
              model.addColumn("Port");
              model.addColumn(" ruta");
              for (int i=0;i<ifiles;i++){               
                   if((listFiles[i][0].contains(file))&&(listFiles[i][3].equals("online"))){
                        String a[]={file,listFiles[i][1],listFiles[i][2],listFiles[i][0]};
                        model.addRow(a);
              return model;          

    And here is the code for the server's Interface:
    public class serverInterface extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JPanel panelSouth = null;
         private JButton buttonStart = null;
         private JButton buttonStop = null;
         private Server servidor = null;
         private JPanel panelNorth = null;
         private JLabel labelConnect = null;
         private JPanel panelCentro = null;
         private JScrollPane scrollPanelClients = null;
         private JPanel panelOnlineClients = null;
         private JLabel labelOnlineClients = null;
         private JScrollPane scrollPanelClients1 = null;
         private JTable tablaClients = null;
         private DefaultTableModel model = new DefaultTableModel();
         public serverInterface(Server servidor) {
              super();
              this.servidor= servidor;          
              initialize();
         public void initialize() {
              servidor.setSize(545, 309);
              servidor.setContentPane(getJContentPane());
              servidor.setTitle("Server");
              servidor.setResizable(false);
              /*this.setSize(545, 309);
              this.setContentPane(getJContentPane());
              this.setTitle("Server");*/
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getPanelSouth(), BorderLayout.SOUTH);
                   jContentPane.add(getPanelNorth(), BorderLayout.NORTH);
                   jContentPane.add(getPanelCentro(), BorderLayout.CENTER);
              return jContentPane;
         private JPanel getPanelSouth() {
              if (panelSouth == null) {
                   panelSouth = new JPanel();
                   panelSouth.setLayout(new FlowLayout());
                   panelSouth.add(getButtonStart(), null);
                   panelSouth.add(getButtonStop(), null);
              return panelSouth;
         private JButton getButtonStart() {
              if (buttonStart == null) {
                   buttonStart = new JButton();
                   buttonStart.setText("Start");
                   buttonStart.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt0) {
                         servidor.buttonPressed(0);
              return buttonStart;
         private JButton getButtonStop() {
              if (buttonStop == null) {
                   buttonStop = new JButton();
                   buttonStop.setText("Stop");
                   buttonStop.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt1) {
                         servidor.buttonPressed(1);
              return buttonStop;
         public void updateVal(int updatedValue,String ip, String port, int numFiles){
              switch(updatedValue){
                 case 1:{  JOptionPane.showMessageDialog(this, "The Server Is Now Online");  //se conecta el server
                            labelConnect.setText("Server Online. Listening on port 7777");
                            buttonStart.setEnabled(false);
                         break;
                 case 2:{ String a[] = {ip,port,numFiles+""};
                           model.addRow(a);                      
                            break;
         private JPanel getPanelNorth() {
              if (panelNorth == null) {
                   GridBagConstraints gridBagConstraints = new GridBagConstraints();
                   gridBagConstraints.gridx = 0;
                   gridBagConstraints.gridy = 0;
                   labelConnect = new JLabel();
                   labelConnect.setText("Server Offline");
                   panelNorth = new JPanel();
                   panelNorth.setLayout(new GridBagLayout());
                   panelNorth.add(labelConnect, gridBagConstraints);
              return panelNorth;
         private JPanel getPanelCentro() {
              if (panelCentro == null) {
                   panelCentro = new JPanel();
                   panelCentro.setLayout(new BorderLayout());
                   panelCentro.add(getPanelOnlineClients(), BorderLayout.NORTH);
                   panelCentro.add(getScrollPanelClients1(), BorderLayout.CENTER);
              return panelCentro;
         private JPanel getPanelOnlineClients() {
              if (panelOnlineClients == null) {
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.gridx = 0;
                   gridBagConstraints1.gridy = 0;
                   labelOnlineClients = new JLabel();
                   labelOnlineClients.setText("Connected Clients:");
                   panelOnlineClients = new JPanel();
                   panelOnlineClients.setLayout(new GridBagLayout());
                   panelOnlineClients.add(labelOnlineClients, gridBagConstraints1);
              return panelOnlineClients;
         private JScrollPane getScrollPanelClients1() {
              if (scrollPanelClients1 == null) {
                   scrollPanelClients1 = new JScrollPane();
                   scrollPanelClients1.setViewportView(getTablaClients());
              return scrollPanelClients1;
         private JTable getTablaClients() {
              if (tablaClients == null) {
                   tablaClients = new JTable(model);
                   model.addColumn("IP Address");
                   model.addColumn("Port");
                   model.addColumn("Files Shared");
                   tablaClients.setEnabled(false);
              return tablaClients;
    }

  • X Server (10.3.9) GUI freezes with spinning wheel

    I have a problem with the GUI interface on an eMac running OS X Server v10.3.9 (Build 7W98, Security Update 2006-006).
    When I login locally (with any kind of user) it ever happens that the GUI freezes during common operations.
    I noticed (or better, it seems) that the problem could be related to the spinning wheel used to graphically inform the user to wait while the operation is progressing. In fact, the GUI freezes (as well as the wheel movement) when I call windows or applications that start the wheel spinning. After less than a couple of seconds everything is frozen except the mouse pointer that, sometimes but not too often, becomes a spinning beach ball. Then it seems it doesn't happen anything more. Only one to ten times, the system restarts after 5 to 10 minutes.
    NOTE WELL that even if the local user is frozen, the server services are working well, without any slowing down.
    I can get out of the problem only if I login as root via ssh with another terminal and launch the classic "shutdown -r now" (of course, also switching off the eMac).
    I've already tried either a permission repair with DiskUtility (booting the system via the original X Server DVD) and running DiskWarrior, but without any results.
    I also tried to unplug the Ethernet RJ45 connector to isolate the unit from the network, but again, no way.
    Any suggestion?
    Thank you very much in advance.
    Regards,
    MrMars96
    eMac   Mac OS X (10.3.9)  

    Hi Jeff,
    thank you for your post.
    What do you consider common operations?
    Browsing folders with Finder, running Software Update, DiskUtility, Server Admin and so on.
    Can you keep the Activity monitor open and see if there
    are any spikes?
    Yes, I can keep the Activity Monitor open (it doesn't have the spinning wheel, and that's another reason I suspect on it or something related to it).
    Sorry for my inexperience, unfortunately I don't know what "spikes" are. I'll surely look for some explanation.
    Have you checked the logs?
    Yes. As far as I saw, there isn't any important error. Have you perhaps any clue to which log should I inspect with big attention?
    Most important, how much RAM do you have. I'd never try an
    OS X Server with less than 2GB.
    Only 512MB. It's a server for 3 people. Mainly for IMAP service and a light Joomla site (so apache+mysql) still work in progress.
    The system worked well for more than a year and half (but Joomla has been installed for 3 months).
    Thank you very much for any kind of support,
    Michael

  • How do I move 'Clear history' back to Tools? Menu editor can't seem to do it. Why are you always making arbitrary GUI changes?

    I want to move the "Clear (Private Data)" menu item back to the tools menu. Menu Editor's dev didn't anticipate this so my usual option for shuffling menu commands around won't work.
    * I know there is a keyboard shortcut to open it.
    * I know it has been moved to the History menu.
    * This is not a question about finding or using the feature, it is about GUI customization.
    Semi-unrelated rant:
    Every time there's a new version of FF I dread installing it because you always make these arbitrary changes. Hiding menus, moving tabs, moving the home button, merging the stop/refresh button, hiding the taskbar, making everything except the domain name in the URL bar too dim to read, defaulting to that silly half-assed speed dial thing as a default home page, merging the title and tab bars, adding jerky acceleration to mouse scrolling, removing the ability to set a time limit for history/cache expiration, treating flash objects the same as cookies, disabling the awesome dialog asking to save your tabs if you close with more than one open, hiding granular javascript/DOM permissions(these now require individual about:config edits.) This is just an off-the-top-of-my-head list of the "upgrades" that I have had to fix over the past couple of years. I was a Netscape user most of my life, and have been a Firefox user ever since. One big reason I still use FF is the fantastic customization; I've been able to fix all of these things to my liking but in any other browser you simply wouldn't be able to change any of them.
    But come on, seriously, stop it. If I wanted to use Chrome I would go install Chrome.

    Hi onetimeuse001,
    Thank you for contacting Mozilla Support and for your feedback. I will certainly recommend opening a Feature Request to have the process for customization reviewed in Bugzilla.
    For alternatives to moving the clear data
    *This customized menu add on might do the trick [https://addons.mozilla.org/en-US/firefox/addon/menu-editor/ Menu Editor]
    *Clear Recent history button on the toolbar I have been using is nice, but might not be what you would like. [[https://addons.mozilla.org/en-US/firefox/addon/clear-recent-history/ ]]
    Also for the next update, so that no data is lost it is possible to preserve the user preferences with the files from the User Profile Folder.
    * C:\Users\<user>\AppData\Roaming\Mozilla\Firefox\Profiles\<profile>\
    cor-el, an awesome contributor always recommends these links:
    *[[http://kb.mozillazine.org/Profile_Manager]]
    *[[https://support.mozilla.org/kb/Managing+profiles ]]
    *[[ http://kb.mozillazine.org/Recovering_a_missing_profile ]]
    Please feel free to ask anymore questions. We are happy to help.

  • Java GUI freezes in Debian/Sarge

    Hi,
    I am running a Debian/Sarge
    #uname -a
    Linux jukebox 2.6.14.2 #5 PREEMPT Mon Nov 28 20:28:54 CET 2005 i686 GNU/Linux
    I have a java casino game created by jdk (1.6.0_02) netbeans(5..5.1) . If I run it in development machine (windows) it runs okay. It also runs okay in (fedora)
    But I got problme when I run it in the Debian. after some clickings and typings it gets frozen. just frozen. I can not work with it. I though I would compile it with netbeans. then I install netbeans. But Netbeans also shows the same behavior. To bo sure, I tried jEdit. The result was same. hang. the GUI.
    I am sure its about Debian vs JDK
    Can you please help me?

    casta2k wrote:
    I tried running a very simple "Hello World" program and it did not work either. The problem is the same: once I place the pointer on top of the window, it freezes and then an error message appears. The code can be found at the following link:
    http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java
    Does anybody know any similar case? ThanksI suspect that your Ubuntu is defaulting to OpenJDk or some other Java/JDK . Remove all Java installations and then install Sun JDK 6 using sun-java6-bin .

  • GUI Freezes but SSH, mouse and audio continue

    Every now and again, my Mac Mini's GUI will freeze except I will be able to move the mouse cursor (not click), whatever audio is currently playing will continue, and I'll have SSH access from my MacBook Pro.  I have SSH'd in and looked at 'top' to see if any processes are hogging the CPU, and I've never seen any out of the ordinary processes.  Sometimes a command of 'sudo shutdown -r now' will restart the computer but other times I have to do a hard reset with the power.
    How else can I diagnose this?  What terminal commands should I be using to discover more information?
    Regards

    Every now and again, my Mac Mini's GUI will freeze except I will be able to move the mouse cursor (not click), whatever audio is currently playing will continue, and I'll have SSH access from my MacBook Pro.  I have SSH'd in and looked at 'top' to see if any processes are hogging the CPU, and I've never seen any out of the ordinary processes.  Sometimes a command of 'sudo shutdown -r now' will restart the computer but other times I have to do a hard reset with the power.
    How else can I diagnose this?  What terminal commands should I be using to discover more information?
    Regards

  • GUI Freezing (but im using- doInBackground() )??

    I have developed a GUI that can runs several different processes.
    Even though each of the processes are called in the same way, only one of these processes causes the GUI to freeze up. (the others do not).
    There are 4 classes involved in this process.
    1) public class myFrame extends FrameView  2) public class myWorkerClass extends SwingWorker<Void,String> 3) public class StreamGobbler implements Runnable4) public class JTextComponentAppendable implements java.lang.Appendable The Frame contains a JTextArea where i put all of the output (and error). And it also calls the WorkerClass as follows:
    private void StepTwoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
            worker = new myWorkerClass();
            worker.setStepTwo(true); // sets necessary fields  for worker.
            worker.execute(); // runs "doInBackground()"
        }The relevent classes in the WorkerClass are "doInBackground()" and "CreateParser()" ( CreateParser() uses the StreamGobbler as shown):
    protected Void doInBackground() throws Exception {  
      if (getStepTwo() == true)
          myGUI.getOutputArea().append("++ CreatingParser ++\n");
          CreateParser();
    protected void CreateParser() throws InterruptedException
            Runtime r = Runtime.getRuntime();
            try {
                proc = r.exec(Command, Environment, WorkingDirectory); // Command, Environment,
                                            //and WorkingDirectory are global variables,
                                            // set elsewhere in the Worker Class
                StreamGobbler output, error;
                output = new WorkerStreamGobbler(proc.getInputStream(),
                                    null, new JTextComponentAppendable( myGUI.getOutputArea()));
                error  = new WorkerStreamGobbler(proc.getErrorStream(),
                                    null, new JTextComponentAppendable( myGUI.getErrorArea()));
                output.start();
                error.start();
                proc.waitFor();
                proc.destroy();
               } catch (IOException ex) {
                   System.err.println("\n ERROR: Could not perform opperation ");
                   ex.printStackTrace();
        }The Gobbler Class is as follows: (it uses the JTextComponentAppendable class - ill put that after this class)
    public class WorkerStreamGobbler implements Runnable
        private final String prefix;
        private final BufferedReader in;
        private final Appendable out;
        private Thread gobblerThread;
         * @param input - InputStream to process (error or output)
         * @param prefix  - optional prefix that can be placed at the front of each string if desired.
         * (For this project the prefix was originally left as ""  (nothing) );
        public WorkerStreamGobbler(InputStream input, String prefix, Appendable output)
            this.prefix = (prefix == null) ? "" : (prefix + ": ");
            this.out = output;
            this.in = new BufferedReader(new InputStreamReader(input));
         * The method used to start processing of the thread on a new thread.
        public void start()
            gobblerThread = new Thread(this, "StreamGobbler: "+prefix);
            gobblerThread.start();
        @Override
        public void run()
            String line = "";
            while(!Thread.interrupted() && line != null)
                try
                    line = in.readLine();
                    if (line != null)
                       out.append(prefix + line + "\n");                  
                } catch (IOException e)
                { /* likely to occur if the input is closed, but
                   * that is okay, just stop reading from it and die.
                    e.printStackTrace();
    }Finally, the JTextComponentApendable is:
    import java.io.IOException;
    import javax.swing.SwingUtilities;
    import javax.swing.text.JTextComponent;
    public class JTextComponentAppendable implements java.lang.Appendable
        private final JTextComponent output;
        public JTextComponentAppendable(JTextComponent toAppendTo)
            this.output = toAppendTo;
        @Override
        public java.lang.Appendable append(final CharSequence input) throws IOException
            SwingUtilities.invokeLater(new Runnable() {
               public void run()
                   if (input == null)
                       output.setText(output.getText() + " null");
                   else
                       output.setText(output.getText() + input);
            return this;
        @Override
        public java.lang.Appendable append(final char input) throws IOException
            SwingUtilities.invokeLater(new Runnable() {
                public void run()
                    output.setText(output.getText() + input);
            return this;
        @Override
        public java.lang.Appendable append(final CharSequence input, final int start, final int end)
                        throws IOException
            SwingUtilities.invokeLater(new Runnable() {
                public void run()
                    if (input == null)
                        output.setText(output.getText() + " null");
                    else
                        output.setText(output.getText() + input.subSequence(start, end));
            return this;
    I was under the impression that if methods called by ".execute()" ( which runs the "doInBackground()" method) would NOT cause the GUI to freeze up.
    Is it possible that the process i started with "proc = r.exec(...)" created another process that was not run in the background? Would that cause the GUI to freeze up?
    Any ideas?
    Edited by: 00jt on Jul 21, 2009 11:47 AM

    Encephalopathic wrote:
    One problem I see is that you're calling Swing stuff from within the doInBackground method and that's a no-no:
    protected Void doInBackground() throws Exception {  
    if (getStepTwo() == true)
    myGUI.getOutputArea().append("++ CreatingParser ++\n"); // Here!
    CreateParser();
    }Why not use process and publish here?I got it working, so it doesn't freeze - (publish and process worked, thanks)... But im wondering if im doing this the wrong way....
    I need to be able to call "publish()" and have the output go to either a "error Textarea" or a "output Textarea"
    So In the worker class I changed a few things:
    public class J_Hats_ParentWorker extends SwingWorker<Void,ProcessingType>{ // Notice "ProcessingType"
    // All of these are newly added:
    protected void outPublish(String p)
           super.publish(new ProcessingType(p, myGUI.getOutputArea()));
        protected void errPublish(String p)
            super.publish(new ProcessingType(p, myGUI.getErrorArea()));
        @Override
        protected void process(List<ProcessingType> myTypes)
            for(ProcessingType p :myTypes)
                    p.myArea.append(p.myString);
        public class  ProcessingType{
         JTextArea myArea;
         String myString;
            ProcessingType(String s, JTextArea a)
               myArea = a;
               myString = s;
        }I then changed my Gobbler to determine if it is "output" or "error".. so the Gobbler does not append text to the GUI, it just sends it to be published
    public class WorkerStreamGobbler implements Runnable
        private final String prefix;
        private final BufferedReader in;
        private boolean out;                       // Instead of getting an Apendable object, i just test which "publish" to call based on this
        private Thread gobblerThread;
         * @param input - InputStream to process (error or output)
         * @param prefix  - optional prefix that can be placed at the front of each string if desired.
         * (For this project the prefix was originally left as ""  (nothing) );
        public WorkerStreamGobbler(InputStream input, String prefix, boolean output)
            this.prefix = (prefix == null) ? "" : (prefix + ": ");
            this.out = output;
            this.in = new BufferedReader(new InputStreamReader(input));
         * The method used to start processing of the thread on a new thread.
        public void start()
            gobblerThread = new Thread(this, "StreamGobbler: "+prefix);
            gobblerThread.start();
        @Override
        public void run()
            boolean check = false;
            String line = "";
            while(!Thread.interrupted() && line != null)
                try
                    line = in.readLine();
                    if (line != null)
                        if(out) // if it should go to the out area
                           myGUI.getWorker().outPublish(line+ "\n");
                        else // if it should go to the error area
                            myGUI.getWorker().errPublish(line+ "\n");
                } catch (IOException e)
                { /* likely to occur if the input is closed, but
                   * that is okay, just stop reading from it and die.
                    Thread.currentThread().interrupt();
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Logger.getLogger(WorkerStreamGobbler.class.getName()).log(Level.SEVERE, null, ex);
                    e.printStackTrace();
    }Finally, inside the Worker i made it so that:
       if (getStepTwo() == true)
           myGUI.getWorker().outPublish("++ CreatingParser ++\n"); // Here!
           CreateParser();
      public void CreateParser()
           Runtime r = Runtime.getRuntime();
            try {
                proc = r.exec(Command, Environment, WorkingDirectory);
            } catch (IOException ex) {
                System.err.println("\n ERROR: Could not perform opperation ");
                ex.printStackTrace();
            WorkerStreamGobbler output, error;
            output = new WorkerStreamGobbler(proc.getInputStream(), null, true);
            error  = new WorkerStreamGobbler(proc.getErrorStream(), null, false);
            output.start();
            error.start();
            proc.waitFor();
            proc.destroy();
    }Does that seem all safe/good to you? Because it seems to work fine.
    Thanks again!

  • Avoid GUI freezing

    I need help on Powershell GUI interface. On long last processes/loops GUI is freezing and I want to avoid that. I want to refresh GUI (richtextbox value) on backgroud or from different runspace.
    I do not think that background job is a solution. Maybe a hastable and different runspace.
    He is my code about this issue. Can anyone give me a better example or edit my code?
    Copy code and save as .ps1
    ********** CODE ***************
    # Source File Information (DO NOT MODIFY)
    # Source ID: 2a715e2e-26db-488f-ab65-742aaad00d98
    # Source File: GUIrefresh.psf
    #region File Recovery Data (DO NOT MODIFY)
    <#RecoveryData:
    UQoAAB+LCAAAAAAABAC9Vl1v2jAUfZ+0/2DlOQJCPigSRCrZOlXrtqrQbm/ISW7Aw7GR7bRkv37O
    B4yWFtKuoEhRjI997rnnxGFwAxG/B5F/wgoj/SAJZ0Oja/gfPyA0+CHIjDBMLwiF7zgF/8vtpYBE
    gJy3ljIZtHcA1bLwN0QKqXwJQ2OcSwVp6ydhMX+QrQsu0upuouemTHRXV+G0OsVloiCjKhMwZJAp
    gamJrrOQkugr5BO+ADYMez3sRq5n9W0HOmd9AzFdytBI9H6WgaI5obHQOCPgTAlOZaVOF3ot+BKE
    yusFASXA1Jj8AcN3PM9EjucO2mvQC4sK2YZfch3ETmClDL/QuQv9fK+5a9wVx3G957R4HrTL2TX0
    cH9HmVKcHb3DYUmzt8e7TbjiEVaa3vCtrolsq7fTi5eaXNM1wFce9lwTde0G8AkOL1kMK11SE3Tp
    YvNibiXcEZlhOlY5hRGOFgGnXBj+RGTw3PrtKOhMRosN27QcPolDu8pD83TckGheiBjx1dEjIjSX
    0lwhX/1XTqxu45hsUzbOiuNokm6/86q0NEKXadnMHrC7QAdzzGYQPxYy3ZrZ4//jwbmUkGqbQK6x
    9S+5X9v+DTM8g1Tv1jrPFE/Ljv+z325qv22FiX3meji2PQdsfWxumJ4ypzLigpLwHUK2h6XSdwqO
    d391DjMWX+vTEAn8QNjsLVwdO3GTXmJZsdvBNj7M9Sulp9FEhH5BuMjHIO5JBG+y7NXqAi7gJPJq
    VfqY0dKOoG0zrE6VQXv7L6T/F10qjVRRCgAA#>
    #endregion
    <#
        .NOTES
         Code generated by:  SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.82
         Generated on:       23.3.2015 14:19
         Generated by:       Administrator
         Organization:       W12
        .DESCRIPTION
            GUI script generated by PowerShell Studio 2015
    #>
    #region Application Functions
    #endregion Application Functions
    # Generated Form Function
    function Call-GUIrefresh_psf {
     #region Import the Assemblies
     [void][reflection.assembly]::Load('mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
     [void][reflection.assembly]::Load('System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
     [void][reflection.assembly]::Load('System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
     [void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
     #endregion Import Assemblies
     #region Generated Form Objects
     [System.Windows.Forms.Application]::EnableVisualStyles()
     $form1 = New-Object 'System.Windows.Forms.Form'
     $button1 = New-Object 'System.Windows.Forms.Button'
     $richtextbox1 = New-Object 'System.Windows.Forms.RichTextBox'
     $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
     #endregion Generated Form Objects
     # User Generated Script
     $form1_Load={
     $richtextbox1_TextChanged = {
      $richtextbox1.Update()
     $button1_Click = {
      # Variables
      $richtextbox1.Text = @()
      # Map an existing hash table to a syncronized variable for use between threads
      $ADHashTable = [HashTable]::Synchronized(@{ })
      $ADHashTable.tmptxt = "Alfa"
      # First value
      $tmp = "First line" + "`n"
      $richtextbox1.AppendText($tmp)
      # Create a new RunSpace
      $ADRunSpace = [RunSpaceFactory]::CreateRunSpace()
      $ADRunSpace.ApartmentState = "STA"
      $ADRunSpace.ThreadOptions = "ReuseThread"
      $ADRunSpace.Open()
      # Set Synchronized hash table variable
      $ADRunSpace.SessionStateProxy.setVariable("ADHashTable", $ADHashTable)
      # Custom code
      $ADPowerShell = [PowerShell]::Create()
      $ADPowerShell.Runspace = $ADRunSpace
      $handle = $ADPowerShell.AddScript({
       # Set simple value
       $ADHashTable.tmptxt = "Beta" + "`n"
       # Core code is here, this may take > 10 minutes.
       # Update GUI (richtextbox) without freezing it.
       # Import new values to GUI richtextbox.
       <#
       # This is simple example
       $ADUsers = Get-ADUser -Filter * -Properties *
       $ADUsers | % {
        # Append user displayName to richtextbox
        # Is is possible to user $ADHashTable.tmptxt variable
       #>
      }).BeginInvoke()
      # Wait for the handle job to finish
      while (-Not $handle.IsCompleted) {
       Start-Sleep -Milliseconds 100
      # Update simple value
      $richtextbox1.AppendText($ADHashTable.tmptxt)
      # Update last value
      $richtextbox1.AppendText("All done")
      # Close the session and dispose of PowerShell object
      $ADPowerShell.EndInvoke($handle)
      $ADRunSpace.Dispose()
     # --End User Generated Script--
     #region Generated Events
     $Form_StateCorrection_Load=
      #Correct the initial state of the form to prevent the .Net maximized form issue
      $form1.WindowState = $InitialFormWindowState
     $Form_Cleanup_FormClosed=
      #Remove all event handlers from the controls
      try
       $button1.remove_Click($button1_Click)
       $richtextbox1.remove_TextChanged($richtextbox1_TextChanged)
       $form1.remove_Load($form1_Load)
       $form1.remove_Load($Form_StateCorrection_Load)
       $form1.remove_FormClosed($Form_Cleanup_FormClosed)
      catch [Exception]
     #endregion Generated Events
     #region Generated Form Code
     $form1.SuspendLayout()
     # form1
     $form1.Controls.Add($button1)
     $form1.Controls.Add($richtextbox1)
     $form1.ClientSize = '466, 465'
     $form1.Name = "form1"
     $form1.Text = "Form"
     $form1.add_Load($form1_Load)
     # button1
     $button1.Location = '12, 317'
     $button1.Name = "button1"
     $button1.Size = '75, 23'
     $button1.TabIndex = 1
     $button1.Text = "button1"
     $button1.UseVisualStyleBackColor = $True
     $button1.add_Click($button1_Click)
     # richtextbox1
     $richtextbox1.Location = '12, 12'
     $richtextbox1.Name = "richtextbox1"
     $richtextbox1.Size = '442, 290'
     $richtextbox1.TabIndex = 0
     $richtextbox1.Text = ""
     $richtextbox1.add_TextChanged($richtextbox1_TextChanged)
     $form1.ResumeLayout()
     #endregion Generated Form Code
     #Save the initial state of the form
     $InitialFormWindowState = $form1.WindowState
     #Init the OnLoad event to correct the initial state of the form
     $form1.add_Load($Form_StateCorrection_Load)
     #Clean up the control events
     $form1.add_FormClosed($Form_Cleanup_FormClosed)
     #Show the Form
     return $form1.ShowDialog()
    } #End Function
    #Call the form
    Call-GUIrefresh_psf | Out-Null

    See the following article:http://www.sapien.com/blog/2012/05/16/powershell-studio-creating-responsive-forms/PowerShell Studio has a specific custom control set
    that does this. It is on the "Control Sets" tab oof the toolbox and is called "Job Tracker Form.
    ¯\_(ツ)_/¯

  • SDM GUI freezes after login

    Hi all!
    I have a problem with my SDM Remote GUI. After starting SDM via RemoteGui.bat, I can log in and the password is accepted.
    But from now the GUI is blank. I see a sandglass and nothing is happening anymore.
    Here are the SDM Logs:
    SDM log:
    Jun 20, 2006 7:42:52 AM  Info:
    Jun 20, 2006 7:42:52 AM  Info: ===============================================
    Jun 20, 2006 7:42:52 AM  Info: =   Starting to execute command 'remotegui'   =
    Jun 20, 2006 7:42:52 AM  Info: ===============================================
    Jun 20, 2006 7:42:55 AM  Info: SDM started successfully.
    GUI log:
    Jun 20, 2006 7:42:55 AM  Info: SDM-Gui is started Jun 20, 2006 7:42:55 AM  Info: Gui is remote - have to connect to server Jun 20, 2006 7:43:09 AM  Info: Attempting to logon to Host "edi5", Port "50018", Role "admin"
    Jun 20, 2006 7:43:14 AM  Info: Logon to host "edi5" was successful Jun 20, 2006 7:43:14 AM  Info: Repository data loaded successfully
    Does anybody know this issue? Help is highly appreciated.
    Kind regards,
    Matthias

    Hii Mathias,
    I am also facing the same problem , and also read the SAP note . But I am facing two problems.
    As given thread explain that Search for ComponentName 2  but when I serarch my Sdmreposiatry.sdc  I found nothing.
    Second I also unable to unserstand The concept of List L1  L2 ...Ln .
    Pls explain step by step.
    Thanks In Advance
    Regards:
    Mayank kumar Saxena
    Edited by: Mayank  Saxena on Oct 18, 2008 1:36 PM

  • GUI freeze problem

    Hi everyone, im having a new problem with my sockets, i want to implement a button to stop server but because its client/server architecture it is freezed, how can i separate interface, please help :S

    Like you say hiwa maybe the problems is the client, i posted in other post, but is not problem to post it again, thanks!!!
    import java.net.*;
    import java.io.*;
    public class RecivirArchivoEncriptado2{
      String fileCharSet;
      String separator;
      Socket clientsocket;
      BufferedReader socketInput;
      String s;
      public RecivirArchivoEncriptado2(){
        fileCharSet = "UTF-8";
        separator = "##$##$##";
        try {
          clientsocket = new Socket("127.0.0.1", 12349);
          socketInput = new BufferedReader
           (new InputStreamReader(clientsocket.getInputStream(), fileCharSet));
        catch (Exception e){
          e.printStackTrace();
       public void doFileGet(){
        try{
          PrintWriter fileOutput
           = new PrintWriter(new FileOutputStream("archivoEncriptado.txt"), true);
          while ((s = socketInput.readLine()) != null){
            if (s.equals(separator)){
              break;
            fileOutput.println(s);
          fileOutput.close();
          fileOutput.flush();
          System.out.println("archivo encriptado recivido");
          fileOutput
           = new PrintWriter(new FileOutputStream("archivoPlano.txt"), true);
          while ((s = socketInput.readLine()) != null){
            fileOutput.println(s);
          fileOutput.flush();
          fileOutput.close();
          System.out.println("archivo plano recivido");
          socketInput.close();
          clientsocket.close();
        catch(IOException e) {
          System.out.println("conection refused port 12345");
      }}

  • GUI freezes randomly

    I am writing a program which communicates with a CLIPS database using JClips library (generally the programs asks some questions and in the end prints an answer, kind of questionnaire). The program randomly freezes. I'll try to describe exactly the proble.
    The main function calls the createAndShowGUI() method which shows an introduction screen with one button on it. The button starts the program. There are three main JPanels. First one with a TextArea (it shows the question) and two buttons (clear,confirm). Second one has a CardLayout with 4 cards (first one with radio buttons, another wict check box, one with text field, and one with a TextPane). When the program starts it adds an Observer and waits for CLIPS. Every message (in a specified format) I receive from CLIPS is precessed in the update mathod. Depending on what kind of message it is it shows apropriate card (radio buttons, check boxes, text field or text pane with an answer). If it is a question, when one selcts preferred answer (using for example radio box) and press the Confirm button a message with an answer is sent back to CLIPS. Then the database responds with another question or if it was th last one it sends an answer (a result of its deduction process).
    This is the place wher the program freezes - after pressing the Confirm button. I really don't know the reason. It doesn't happen every time I run the program (about 15% probability that it hangs ;)) and it doesn't happen in a specific moment of the questionnaire.
    This is my first Java program (and first object-oriented program) so this might be really basic problem.
    The source code: http://avatar02.republika.pl/ExpertSystem.java

    I've implemented these techniques and here is what it prints. This is the part of method responsible for printng.
    System.out.println("\t" + stackEntry.getClassName()
              + "." + stackEntry.getMethodName() + " ["
              + stackEntry.getLineNumber() + "]");And this is part of a log that these debug methods print out:
    Event [19297865] java.awt.event.MouseEvent is taking too much time on EDT (563)
    AWT-EventQueue-1 / BLOCKED
         sun.awt.AppContext.get [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.JComponent.repaint [-1]
         java.awt.Component.repaint [-1]
         javax.swing.plaf.basic.BasicButtonListener.stateChanged [-1]
         javax.swing.AbstractButton.fireStateChanged [-1]
         javax.swing.AbstractButton$Handler.stateChanged [-1]
         javax.swing.DefaultButtonModel.fireStateChanged [-1]
         javax.swing.DefaultButtonModel.setPressed [-1]
         javax.swing.plaf.basic.BasicButtonListener.mouseReleased [-1]
         java.awt.Component.processMouseEvent [-1]
         javax.swing.JComponent.processMouseEvent [-1]
         java.awt.Component.processEvent [-1]
         java.awt.Container.processEvent [-1]
         java.awt.Component.dispatchEventImpl [-1]
         java.awt.Container.dispatchEventImpl [-1]
         java.awt.Component.dispatchEvent [-1]
         java.awt.LightweightDispatcher.retargetMouseEvent [-1]
         java.awt.LightweightDispatcher.processMouseEvent [-1]
         java.awt.LightweightDispatcher.dispatchEvent [-1]
         java.awt.Container.dispatchEventImpl [-1]
         java.awt.Window.dispatchEventImpl [-1]
         java.awt.Component.dispatchEvent [-1]
         java.awt.EventQueue.dispatchEvent [-1]
         TracingEventQueueJMX.dispatchEvent [18]
         java.awt.EventDispatchThread.pumpOneEventForFilters [-1]
         java.awt.EventDispatchThread.pumpEventsForFilter [-1]
         java.awt.EventDispatchThread.pumpEventsForHierarchy [-1]
         java.awt.EventDispatchThread.pumpEvents [-1]
         java.awt.EventDispatchThread.pumpEvents [-1]
         java.awt.EventDispatchThread.run [-1Could you please help me analyse this output? ;)
    Thanks for replies.
    Edited by: Avatar on Nov 29, 2007 10:26 AM

  • Problem with Itunes making my computer freeze

    Hi there i've got a frustrating problem. Whenever I open Itunes, my mouse freezes and my computer takes a very long time to load itunes. If I leave the mouse alone, Itunes will seem to work fine, srcolling through the top banners without problems, but everything freezes whenever I move my mouse. this happens only when iTunes is open. What's the deal?
    Thanks, Zach

    Nevermind! i manually installed the update and the problem is gone.

Maybe you are looking for