Updating GUI

Hello Techies,
How can i update my gui.
My gui is having 2 combo boxes , one text field and one button. when i click on button the request must go to the TCP server and receive the responses from TCPServer.
My problem is that when i first click on Button,the request is going to the TCP and getting reply.
I will get continuous responses from TCP server.
I am getting first response from the server.
Second response I am getting the following error.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
     at javax.swing.JComponent.getComponentGraphics(Unknown Source)
     at javax.swing.JComponent.paint(Unknown Source)
     at javax.swing.JComponent.update(Unknown Source)
     at testForSwing1$4.run(testForSwing1.java:475)
     at java.awt.event.InvocationEvent.dispatch(Unknown Source)
     at java.awt.EventQueue.dispatchEvent(Unknown Source)
     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.run(Unknown Source)Here is my Code
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfigTemplate;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class testForSwing1 extends JPanel implements ActionListener {
    public static Socket socket ;
       JTextField textField;
       JComboBox exchangeComboBox;
       JComboBox fieldsComboBox;
       JButton button;
        public testForSwing1(List List, List )
     super();
     // TODO Auto-generated constructor stub
     JLabel exchLabel = new JLabel("xxxName");
     xxxComboBox = new JComboBox(List.toArray());
     add(xxxLabel);
     add(xxxComboBox);
                      xxxComboBox.addActionListener(this);
     out = outStream;
     in = inStream;
     JLabel fieldLabel = new JLabel("yyy");
     fieldsComboBox = new JComboBox(fieldsList.toArray());
     add(fieldLabel);
     add(fieldsComboBox);
     fieldsComboBox.addActionListener(this);
     textField = new JTextField(15);
     add(textField);
     button = new JButton("clickMe");
     button.addActionListener(this);
     add(button);
     public void actionPerformed(final ActionEvent ae)
     final  JButton ts = (JButton)ae.getSource();
     if ((ae.getActionCommand().equalsIgnoreCase("clickMe"))) {
     //try
     Runnable tcpConnection = new Runnable()
     public void run()
              try
                    out = new DataOutputStream(socket.getOutputStream());
                      in = new DataInputStream(socket.getInputStream());
                                                                                      out.writeBytes(ram);                               
              out.writeByte('\n');
                                                                 while(socket.getInputStream()!= null)
         System.out.println("echo: " + in.readLine());
         update( grap );
catch (IOException ioe) {
                     System.out.println("IOException"+ioe.getMessage());
                                             SwingUtilities.invokeLater(tcpConnection);
                              break outt;
      * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          //List list1InMainMethod = new ArrayList();
          //List list2InMainMethod = new ArrayList();
              try {
               File sourceXmlFile = new File(args[0]);
               File fidsXmlFile = new File(args[1]);
               DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                         .newInstance();
                socket = new Socket("test",90);
     createAndShowGUI(xxxFile, yyyFile);
          } catch (ParserConfigurationException pce) {
               // TODO: handle exception
               System.out.println("ParserConfiguration exception"
                         + pce.getMessage());
          } catch (SAXException saxe) {
               // TODO: handle exception
               System.out.println("SAXException" + saxe.getMessage());
          } catch (IOException ioe) {
               // TODO: handle exception
               System.out.println("IOExceptionxxxx" + ioe.getMessage());
public static Graphics grap;
     public static void createAndShowGUI(List list1InCreateAndShowGUI,
               List list2InCreateAndShowGUI,DataOutputStream out,DataInputStream in) {
          // Make sure we have nice window decorations.
          //try
          JFrame.setDefaultLookAndFeelDecorated(true);
          // Create and set up the window.
          JFrame frame = new JFrame("ComboBoxDemo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     JComponent newContentPane = new testForSwing1(list1InCreateAndShowGUI,
                    list2InCreateAndShowGUI,out,in);
          newContentPane.setOpaque(true); // content panes must be opaque
          //grap = newContentPane.getGraphics();
          frame.setContentPane(newContentPane);
          // Display the window.
          frame.pack();
          frame.setVisible(true);
}I had posted only GUI coding only..
SwingUtilities.invokeLater(new Runnable()
                   public void run()
                                    try
                                          out = new DataOutputStream(socket.getOutputStream());
                                          in = new DataInputStream(socket.getInputStream());
                                          //Change
                                         out.writeBytes(s);                               
                                          out.writeByte('\n');
                                          //change over
                                        while(socket.getInputStream()!= null)
                                       System.out.println("echo: " + in.readLine());
                                       Object c = in.readLine();
                                       update(grap);
                                    catch (IOException ioe) {
                                             // TODO: handle exception
                                         System.out.println("IOException"+ioe.getMessage());
          I am getting nullpointer exception in update(grap);
If i dont use this update(grap) my gui is going to block.
How can i solve this problem. Plz guide me. I had stucked here very long time back.
Thanks(Inadvance),
ramu.

Hello camie,
The above problem is working fine when i create thread for each request.
when i use nio,instead of threading, the gui is not responding i.e going to be stucked.
I am using nio , since the response from the Server which is appearing in the console is sometimes is machine code, some times some of the characters in the response is missing.
Here is my code.
public class JabberClient1
      testForSwing1 tfs1 = new testForSwing1();
      public void connect(String s,testForSwing1 tfs,SocketChannel  scc,Selector see)throws IOException
           SocketChannel sc = scc;
           Selector sel = see;
          String str = s;
           tfs1=tfs;
          try 
                  int i = 0;
      // Because of the asynchronous nature you do not know
      // when reading and writing is done, hence you need to
      // keep track of this, boolean written is used to
      // alternate between read and write. Whatever is written
      // is echoed and should be read.
      // boolean done is used to check when to break out of
      // the loop
      boolean written = false, done = false;
      String encoding = System.getProperty("file.encoding");
      Charset cs = Charset.forName(encoding);
      ByteBuffer buf = ByteBuffer.allocate(1024);
        while(!done) {
        sel.select();
        Iterator it = sel.selectedKeys().iterator();
          while(it.hasNext()) {
          SelectionKey key = (SelectionKey)it.next();
          it.remove();
          tfs1.repaint();
          sc = (SocketChannel)key.channel();
          if(key.isConnectable() && !sc.isConnected()) {
               System.out.println("is connected");
            InetAddress addr = InetAddress.getByName(null);
          if(key.isReadable() ) {
            if(sc.read((ByteBuffer)buf.clear()) > 0) {
                                  System.out.println("is reading()");
                 String response = cs.decode(
                (ByteBuffer) buf.flip()).toString();
              System.out.print(response);
              if(response.indexOf("END") != -1)
              done = true;
              tfs1.repaint();
          if(key.isWritable() &&!written ) {
               System.out.println("is writting");
             System.out.println("string length"+s.length()); 
            if(i < s.length())
                 sc.write(ByteBuffer.wrap(new String(s+ '\n').getBytes()));
            else if(i == s.length())
                 sc.write(ByteBuffer.wrap(new String("END\n").getBytes()));
            written = true;
          tfs1.repaint();
            i++;
    } finally {
      sc.close();
      sel.close();
  in my testForSwing1.java program
  public static void main(String[] args)
            sc = SocketChannel.open();
            sel = Selector.open();
            sc.connect(new InetSocketAddress("localhost", 7890));
            sc.configureBlocking(false);
            sc.register(sel, SelectionKey.OP_READ |
                                   SelectionKey.OP_WRITE  |  SelectionKey.OP_CONNECT);
JabberClient1 jc= new JabberClient1();
System.out.println("sxxxxxxx"+s);
try
     jc.connect(s,tfs,sc,sel);
catch (IOException e)
     System.out.println("ioexception"+e.getMessage());
              Second code which i had placed is not complete.
my gui is not respondin when the i want to second request.
plz guide me.....
regards,
ramu.

Similar Messages

  • (paid support) Pacman Update GUI

    Below the project description. If you are interested in doing this programming job, please email/pm me.
    If there are questions, please reply to this post.
    Pacman Update GUI
    Archlinux (http://www.archlinux.org/) uses the pacman package manager. A number of GUI applications to control this package manager exist (http://wiki.archlinux.org/index.php/Pac … _Frontends), but none suit our needs.
    For this project you will need to design and implement two independent GTK+ applications: an Update Manager and an Update Applet. The Update Manager must be an application that guides the user through updating the system. The Update Applet must be an application which shows a systray icon. This application will check for updates once in a while and notify the user if there are updates.
    Both applications must be internationalized/localized and written in C, C++ or Python. The applications should have as little dependencies as possible. The applications must include installation scripts. The applications must be installed in compiled form. Any configuration needed for these tools should be systemwide. We do not need a gui for configuration.
    Update Manager
    The Update Manager must be an application that guides the user through the steps of updating the system with as little effort and as little user interaction as possible. You are expected to first define the minimal amount of steps required, design the application and then implement the application (gui and internals).
    There are two possibilities for this applications:
    1. You develop it from scratch.
    2. You modify the gnome update manager (used in eg ubuntu) to work with pacman.
    We will rely on your expertise to decide which approach is best.
    Update Applet
    The Update Applet provides a systray icon which checks for system updates in regular intervals. The applet should have a tooltip showing the update status, and a context menu with a few options, such as "Check for updates now", "About" and "start Update Manager". You are expected to design and implement the application.

    I don't get why you should allow your users to update their OS(that is their GUI, their kernel, xorg, libc and other _core_ functionality). These components are already quite "great" and shouldn't need upgrading if that is your worry. Only in the case of some new device coming out and the kernel or xorg need to support it i can see the problem. This should happen very rarely though. I mean, why should you allow your OS to be upgraded by some lowly non-tech users. I don't know of many workplaces which allow their users to upgrade their windows versions for example...
    You could always upgrade the OS every X years if needed.
    If the boss wants his emplyees to be able to download whichever apps/games they want then ofcourse you could allow this, but this should only be allowed if said apps/games doesn't drag in new versions of xorg, kernel versions or other core functionality or its dependencies.
    Just blacklist these in pacman.conf and make the file unwritable for the users...
    This way you only need external repo for apps which doesn't install without user intervention.
    Here i define "core functionality" as all the code responsible for giving a "working computer" as defined by the boss and you if he's not very IT. If you are worried about security and this is why you want a constantly updating machine then just connect all the machines to a router/firewall before they are allowed onto the net. That one could be an arch machine...
    Also I haven't tried xfce in a long while but you should watch against giving "windows users/mac users" anything which isn't glitzy and full-featured, because if the users doesn't think the OS have all the functionality they "need" and they don't think it looks fancy enough they have a tendency to go back to whatever OS they came from or try to "upgrade" their own os... which might spell problems for you.
    You know, never underestimate the ingeniousness of an idiot.
    Just my 5 cents.
    Last edited by test1000 (2010-06-25 00:13:42)

  • Is it safe to use SwingUtilities.invokeLater(), while updating GUI?

    Hi,
    I am updating GUI components in synchronized block which is runinng on main() thread my application hangs, but if I use SwingUtilities.invokeLater(...) then it runs fine.
    My question is:
    Is it safe to use SwingUtilities.invokeLater(...) in synchronized block.
    Edited by: Amol_Parekh on Nov 1, 2007 1:28 AM

    Paul Hyde in his "Java Thread Programming" (great book!!!) says it is.
    With invokeLater() you say to the Thread Scheduler you want that code to run on the Swing thread. In fact, if that is the only thing you do in the synchronized block I think it is unnecessary.
    Greetings,
    astrognom

  • Possible to update gui with new thread AND halt program execution?

    Hello, my problem is the following:
    I have a JButton that performs a sql query and retrieves information from a database, while this is done I would like to update a JLabel with information that the query is in progress. I have got this working but the problem is that I would like the main thread to wait until the search thread has finished execution, of course this inflictes with the gui update... look below for code:
    //class that synchronizes the threads when retrieving data
    public class SynkroniseradVektorKlass
       private Vector verde = new Vector();
       private boolean inteFerdig=true;
       public SynkroniseradVektorKlass(boolean inteFerdig)
          this.inteFerdig=inteFerdig;
       //sets the value of the vector
       public synchronized void settVerde(Vector verde)
           this.verde=verde;
           //set the boolean to false so the wait() can be avoided
           inteFerdig=false;
           //notify all threads that we have retrieved a value
           notifyAll();
        public synchronized Vector returneraVerde()
            //if no value has been retrieved, wait
            if(inteFerdig)
               try
                    wait();
               catch(InterruptedException ie){}
        //when waiting is done, return value
        return verde;
    //class that retrieves data and prints it
    //not really necessary here but useful to check that the SynkronisedVektorKlass
    // works
    public class TradHarDataKommit extends Thread
       private SynkroniseradVektorKlass hemtaData;
       public TradHarDataKommit(SynkroniseradVektorKlass hemtaData)
          this.hemtaData=hemtaData;
       public void run()
           System.out.println("Thread two begins");
           System.out.println("data == "+hemtaData.returneraVerde());
           System.out.println("Thread two done");
    //class that communicates with the database and retrieves the data
    public class NyTradKorSQLSats extends Thread
       private String sqlSats;
       private java.util.Timer timer;
       private JLabel label;
       private JFrame ram;
       private SynkroniseradVektorKlass tilldelaData;
       public NyTradKorSQLSats(String sqlSats,java.util.Timer timer,JLabel ,SynkroniseradVektorKlass tilldelaData,JFrame ram)
          this.sqlSats=sqlSats;
          this.timer=timer;
          this.label=label;
          this.tilldelaData=tilldelaData;
          this.ram=ram;
       public void run()
           System.out.println("Thread one begins...");
           //executes the sql query and retrieve data
           tilldelaData.settVerde(klient.korKlient(sqlSats));
           //end the timer that updates the JLabel
           timer.cancel();
           label.setText("");
           ram.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
           System.out.println("Thread one done...");
    //in actionPerformed
    java.util.Timer timer = new java.util.Timer();
    //boolean used to show when execution is done          
    boolean sokningInteFerdig=true;
    //class that holds a value retrieved from database and make sure that
    //everything is synchronized
    SynkroniseradVektorKlass dataFranSokning = new SynkroniseradVektorKlass(sokningInteFerdig);
    //class that retrieves information from dataFranSokning     
    TradHarDataKommit skrivUtData = new TradHarDataKommit(dataFranSokning);
    //class that executes sql query, with arguments sql, a timer that updates
    //the JLabel,the JLabel,the dataholding class, and a JFrame     
    NyTradKorSQLSats korTrad = new NyTradKorSQLSats("1Select namn from kundregister where kundnr=1",timer,statusRad,dataFranSokning,this);
    //a TimerTask class that updates the JLabel               
    TimerStatusRad task1 = new TimerStatusRad(statusRad,"Searching...",this);
    TimerStatusRad task2 = new TimerStatusRad(statusRad," ",this);
    //starts timer task1 directly and restarts every second
    timer.schedule(task1,0,1000);
    //starts timer task 2 after a second and restarts every second after     
    timer.schedule(task2,1000,1000);
    //set the sqlthread to daemon
    korTrad.setDaemon(true);
    //starts the thread                         
    korTrad.start();
    //I would like that the program halts here until korTrad is done
    //because the data retrieved are to be used further in the program
    //There is no point in using join(); because this would halt the update of the guiif anyone got any ideas how to solve this please help me
    ps. sorry about my english, its not my native language

    Was not able to review all of your code. But take a look at wait() and update() methods - they should solve what you need.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • Best way to update GUI

    Hi, I have a 'business model' class which holds all my variables that are displayed on my GUI which is a seperate class. As these variables change quite frequently while running the program I need some advise on the best way to update my GUI as need be. I'm using a controller with actionListeners to deal with changes going in the opposite direction. So can I manipulate this approach to suit my needs or should I implement Observable which I've read somewhere else?

    user8844058 wrote:
    Yea that sounds viable to me too DrClap I just can't seem to find any examples of it in action! Would you use events in a non GUI class to achieve this?A bit late - NY time here.
    Example:
    1. User enters data on a GUI;
    2. A button is hit on the GUI and some data is taken as user entries and sent to the contoller;
    3. The controller uses that data and acts as a dispatcher to act on what is requested by calling whatever business logic is required, and the model gets populated appropriately;
    4. Once the model is populated the relevant results are returned to the GUI;
    5. The GUI now represents the results of that population.
    I realize you marked your question as answered, but was, or is your question: "how does (or what is the best or most oftenly used way that) the GUI (view) gets, or knows to get the results of the request?"
    Edited by: abillconsl on Apr 13, 2011 12:42 PM

  • Auto update GUI from server

    Goodmorning,
    i have installed over server "SAP Setup Administrator server" for mantain a gui with centralized deployment.
    I do some upgrade to packages.
    For put this new version of package i see in documentation that i must insert an "SAP Automatic service update".
    I not found this in marketplace, where are i can found?
    thanks

    Right click your gui icon in the desktop -> configure auto-update -> activate auto-update..
    Hope that help
    Juan

  • Continuously Updating GUI

    Hi,
    I'm just wondering whats the best way to write a VI that includes two parts: one being an event driven GUI and the second being a continuously updating data display (i.e. temperature displays and graphs)? Would the only way to accomplish this to have both the controls and data collection incorporated in one loop and forget about an event structure? Both controls and data collection is for the same device and each command/query requires sufficient time for the device to process. 

    No, have the GUI display the data as well as have an event driven "control" part but put the data acquisition in another loop (or better yet another vi). They can communicate through any number of means; functional globals, queues, etc. Search on Producer-Consumer structures, both here (forum) and in the LabVIEW examples in your LabVIEW installation.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Problems updating gui in JApplet

    Hi,
    I have a JApplet with a JPanel with another JPanel ? TreePanel ? containing a JScrollPane with a JTree.
    When init() is run in MyApplet, treePanel is initiated with a JTree, with test data hardcoded in TreePanel?s constructor. I want the tree to change every time a thread loops, by calling method treePanel.updateResultTree(root) from the thread, with a new root. To test this, I have hardcoded a new tree content in the thread to pass to the TreePanel. In method updateResultTree(root), I remove the existing JTree from JScrollPane and add a new JTree to it, with the new root. Then I repaint the JScrollPane.
    When I run the applet, the initial tree is displayed, but it is not updated with the new JTree for the first thread loop as expected. How is the gui in a JApplet refreshed/updated?? Will SwingWoker update the gui automatically without forcing repaint()?
    Please help, I'm so stuck! Thanks in advance!
    MyApplet
    public class MyApplet extends JApplet {
       private TreePanel _treePanel;
       private UpdateHandler _updateHandler;
       private Thread _updateThread;
       public void init() {
          super.init();
          _treePanel = new TreePanel();
          // Updating thread
          _updateHandler = new UpdateHandler();
          _updateThread = new Thread(_updateHandler);
          _updateThread.start();
          // Initialize gui
          JPanel bigPanel = new JPanel();
          bigPanel.setLayout(new BoxLayout(bigPanel, BoxLayout.X_AXIS));          
          getContentPane().add(bigPanel, BorderLayout.CENTER);   
          _treePanel = new JPanel();
          bigPanels.add(_treePanel);
       // Updates the GUI every X seconds
       private class UpdateHandler implements Runnable {
          public final static int UPDATE_INTERVAL = 10;
          public UpdateHandler() { }
          public void run() {
             try {
                _displayResults();
             } catch (InterruptedException ie) {
       private synchronized void _ displayResults () throws InterruptedException {
          while(true) {
             // Resolve a new DefaultMutableTreeNode object as root to be updated in GUI
             // (For test)
             DefaultMutableTreeNode root = new DefaultMutableTreeNode(new Result("Root"));
             DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode(new Result("Result X"));
             DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode(new Result("Result Y"));
             DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode(new Result("Result X1"));
             root.add(child_1);
             root.add(child_2);
             child_1.add(child_11);
             // Update the GUI 
             _treePanel.updateTree(root);
             wait(UPDATE_INTERVAL*1000);
    }TreePanel
    public class TreePanel extends JPanel {
       private JScrollPanel _treeSrcoll;
       private JTree _tree;
       TreePanel() {
          super();
          // Test tree, displayed in applet?s init()
          DefaultMutableTreeNode root = new DefaultMutableTreeNode (new Result("Root"));
          DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode (new Result("Result 1"));
          DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode (new Result("Result 2"));
          DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode (new Result("Result 4"));
          DefaultMutableTreeNode child_12 = new DefaultMutableTreeNode (new Result("Result 5"));   
          root.add(child_1);
          root.add(child_2);
          child_1.add(child_11);
          child_1.add(child_12);
          _tree = new JTree(root);
          _treeScroll = new JScrollPane(_tree);
          add(_treeScroll, BorderLayout.CENTER);
       public void updateTree(DefaultMutableTreeNode  theRoot) {
          if (theRoot != null) {
             if (_tree!= null) {
                _treeScroll.remove(_tree);
             _ tree = new QCTree(root);     
             _treeScroll.add(_tree);
          } else {
             JLabel label = new JLabel("No result tree structure is available");
            _treeScroll.add(label);
         _treeScroll.repaint();
    }Result
    public class Result {
       private String _name; 
       public Result(String name) {
          _name = name;
       public String toString() {
          return _name;

    I found the error:
    I need to use
    treeScroll.getViewPort().add(tree);
    and
    treeScroll.getViewPort().remove(tree);

  • Updating GUI unsafely ...

    Well, still the timer problem. I did something with another thread, it did work. But I don't know how to update the label safely. Please give me some advice. Thanks.
    Here is my current code, not safe...
    public class Clock extends JFrame {
    //    bla ... bla ...
        String time_now = "Moron";
        public Clock () {
    //    bla... bla ...
            SetTime st = new SetTime ();
            st.start();
        public class SetTime extends Thread {
         public void run () {
              try {
              while ( true) {
                  times = (GregorianCalendar)Calendar.getInstance ();
                  int h = times.get(Calendar.HOUR_OF_DAY);
                  int m = times.get(Calendar.MINUTE);
                  int s = times.get(Calendar.SECOND);
                        time_now = configTime(h,m,s);
                        // This is unsafe ----------------------
                        time_display.setText(time_now);
                        sleep(1000);
                 catch ( InterruptedException ie ) {
              System.out.println("Thread Interrupted !");
    }

    What exactly do you mean by "not safe"?
    To prevent concurrent modification of text from different threads: for your time_display you may subclass JLabel (or what have you)
    to make setText(String) synchronized, like this:
    class MyLabel extends JLabel {
        synchronized setText(String text) {
            super.setText(text);
    public class Clock extends JFrame {
        JLabel time_display = new MyLabel();
    }You may also want to use javax.swing.Timer or java.util.Timer, because your implementation does not make a wise use of processing resources. Advantage of using javax.swing.Timer is that its ActionListener's actionPerformed(ActionEvent) method will be executed from the GUI thread � which may just the thing you are asking about.

  • Updating GUI Immediately In Event Dispath Thread

    when i trying to update a GUI (ie: progressBar.setValue(30)) in a event dispath thread (ie: a button click action performed event), it wont updated immediately.
    it is understandable since the action to update the progress bar will also be done in a event dispatch thread. we need to wait until the button click action performed method return (which also run in a event dispatch thread), then only the progress bar updating will be performed.
    i was wondering whether there is a way the progressBar will be update immediately. i had try to do frame.update(frame.getGraphics()) - the progress bar is reinside the frame. it work but slow since it need to update the entire frame.
    is there any better way? i am not sure whether progressBar.paintImmediately is a good way?
    thank you very much!

    >
    No, you have one call to the
    SwingUtilities.invokeLater, with that block of code
    containing all the GUI update code.i dont understand how can we have one call to the SwingUtilities.invokeLater to contain all the GUI update code?
    imagine
    ==== this code is running in another thread===
             // long processing........ blah blah blah
            SwingUtilities.invokeLater(new Runnable() {
                   public void run() {                            
                       progressBar.setValue(1);
            // another long processing........ blah blah blah
            SwingUtilities.invokeLater(new Runnable() {
                   public void run() {                            
                       progressBar.setValue(2);
            // another another long long processing...... blah blah blah
            SwingUtilities.invokeLater(new Runnable() {
                   public void run() {                            
                       progressBar.setValue(3);
            });it seems that we need to make a lot of call to SwingUtilities.invokeLater.......

  • J2ME update gui while running MIDlet

    Hello all,
    I've got a method in my MIDlet which is to show a new form for about 2 seconds and then revert back to the application. It already does all of it's calculations right but it simply does not update the GUI until after the 'return' statement.
    Does anybody know why it does not update the GUI before waiting those two seconds and how could I make it do that? Below is my (greatly oversimplified) code.
         public int Throwing(int diceResult)
                   Form fi = new Form( "Dice" );
                   fi.append("lalala");
                   getDisplay().setCurrent( fi );
              Thread currentThread = Thread.currentThread();
              try {
                   synchronized(this)
                   System.out.println("waiting");
                     wait( 2000 );
                   catch ( InterruptedException ie )
                        System.out.println("Exception caught");
                   System.out.println("Returning");
                 return diceResult;
         }

    What do you mean "the main 'UI' thread continues'. Of course it does. Otherwise your MIDlet becomes unresponsive, as you have seen.
    I imagine what you want is something to be done when Throwing() finishes (like setting a new displayable with the results). In that case you have to make that part of the thread that calls Throwing(). Something like this, maybe:
    public void run() {
      int result = Throwing(5);
      Form f = new Form("Results");
      f.append("The result is " + result);
      getDisplay().setCurrent(f);
    }shmoove

  • Update GUI during db query

    Folks'es,
    i have the following problem:
    * i have to perform a database query during a drag operation
    * the query can take quite some time
    * while the query is performed, i would like to show at least some text in my GUI telling the user what happens
    * i need to wait for the query to finish before i can continue.
    question:
    how can I update the GUI while a lengthy, synchronous operation is done on the event thread?
    thomas
    PS: i know about SwingUtilities.invokeLater() but i can't get it to do what i need (i'm too thick :().

    I recommend the paintImmediately() method. Here is a
    thread that shows it in action:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=23
    114you're a hero! i must have been blind for the last 4 yrs!
    thanx,
    thomas

  • Problem update GUI

    My problem is that when i make a connection and try too update the GUI de gui does not update:
    My question is how can i update the GUI from a thread, the server starts in a thread and when a client connects a new thread is initiated.
    Please Help?
    Code Server:
    package src;
    import javax.swing.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Server  {
       ServerSocket server = null;
       ComputerView computerview = new ComputerView();
        public void listenSocket(){
            try{
              server = new ServerSocket(4444);
            } catch (IOException e) {
              System.out.println("Could not listen on port 4444");
        while(true){
              Client w;
              try{
                w = new Client(server.accept(),computerview.getPanel());
                Thread t = new Thread(w);
                t.start();
              } catch (IOException e) {
                System.out.println("Accept failed: 4444");
    code Client:
    package src;
    import javax.swing.*;
    import java.net.Socket;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.awt.*;
    class Client implements Runnable {
      private Socket client;
      computerIcon CI;
      JPanel paneel = new JPanel();
      ComputerView computerview = new ComputerView();
      boolean aap = true;
            BufferedReader in = null;
        PrintWriter out = null;
      Client(Socket client, JPanel panel) {
       this.client = client;
       paneel = panel;
      public void run() {
        try{
          in = new BufferedReader(new InputStreamReader(client.getInputStream()));
          out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e) {
          System.out.println("in or out failed");
        String inputLine=null;
        out.println("Hello Client");
         while ( aap== true){
                try{
                 inputLine = in.readLine();
                }catch(Exception e){
                 System.out.println(e);
                String state = "WAITING";
                System.out.println(state);
                if(state.equals("WAITING")){
                    if (inputLine.equals("ID")){
                       System.out.println("Client :"+inputLine );
                          out.println("Who are you?");
                          state = "WAITINGFORID";
                          System.out.println(state);
                if(state.equals("WAITINGFORID")){
                    SwingUtilities.invokeLater(new Runnable() {
                    public void run(){
                    JOptionPane.showMessageDialog(paneel,"Verkeerd Inlognaam en/of Wachtwoord!");
                               setComputer("Izzy",new ComputerControl());
                               computerview.jLabel7.setText("Probleem");
                    out.println("You are now Registred!");
                       state = "WAITING";
                       System.out.println(state);
      public void setComputer(String nr, ComputerControl p0){
            CI = new computerIcon(nr);
            CI.getLabel().addMouseListener(p0);
            CI.getLabel().setVerticalAlignment(javax.swing.SwingConstants.TOP);
            System.out.println(CI.getLabel());
            paneel.add(CI.getLabel());
            paneel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
            paneel.updateUI();
            System.out.println(paneel);
            paneel.validate();
    }

    My question is how can i update the GUI from a thread,Read: Threads and Swing

  • Updating guis

    hi,
    i'm currently having a small bit of a problem with a program i'm writing. Basically, i have a gui - when the user clicks on a specific button, I want the system to simultaneously perform a long algorithm and update the gui. When using threads, I set the first one to perform the algorithm and the second one to update the gui. In the case of updating the gui, what i need to happen is for a new list of options to appear on the existing gui but i need this to appear while the other thread is performing the algorithm. I am using the paintImmediately() method but whats happening is that the gui is not being updated until after the thread performing the algorithm is complete. i cant afford to let this happen as it seems to be really slow and unresponsive. Does anyone know any alternate ways to get around this (hope i explained it alright)
    any help much appreciated

    it sounds like the thread performing the algorithm is doing all the work and then updating some data - so i'd guess it needs to tell the gui thread that more information is available while it is executing..
    you could either pass in a JComponent to update (bad practice but quick and dirty) or you could have the algorithm write to some structure which is the meat of a model used by a JComponent

  • ActionEvent triggered from CommandButton not updating GUI

    Hi,
    I’ve a commandbutton an actionListener as show, and had hoped that pressing this button would display updated values for the outputText component
    <h:commandButton actionListener="#{dashBoardBean.displayLastWeek}" value="Last Week"  styleClass="logbt" />
    <h:outputText value="#{dashBoardBean.chartType}" />Associated methods from DashBoardBean
    import javax.faces.event.ActionEvent;
    private String chartType = "thisWeek";
         * @return the chartType
        public String getChartType() {
            return chartType;
         * @param chartType the chartType to set
        public void setChartType(String chartType) {
            this.chartType = chartType;
        public void displayLastWeek(ActionEvent ae) {
            chartType = "lastWeek";
        }However the output is not being updates and pressing the button has no effect..... Hopefully someone can point out what I am doing wrong
    Thanks....

    Do you have <h:messages/> on your page?
    Have you tried to verify if the action listener method is actually called?
    What is the scope of your bean?
    Have you tried the smallest possible example to reproduce the problem?

Maybe you are looking for