Use of SwingUtillities.invokeLater

While reading through the Java Tutorial section on SWING, I noticed that it recommended to always use SwingUtillities.invokeLater for all of the code involved in setting up the GUI.
I recently converted two of my programs that I have been working on using this, and I'm coming up with a small problem:
The GUI will not appear in the Frame. At least, not until I resize the Frame (which would of course trigger the frame to re-layout and re-draw it's components). This has happened in BOTH of my programs that I modified this way.
They are VERY LARGE programs, so I can't post all the code, but has anybody ever come across this problem before? Does anybody know what I might be doing wrong?
Does that fact that my gui is an applet cause this problem? Does the init method already take care of this? Also, I make use of the MainFrame class from the Java 3D API to run it as stand-alone. Could that be causing the problem?

You use SwingUtilities to update the UI from any thread that is not the event dispatch thread. The EDT is the one that listeners get fired on, so you don't have to do that there.
The main method in an app is invoked in a thread that is not the EDT, so you should use it there to trigger code to load the UI.
The init method in an applet is (as far as I know) run in the EDT, so you shouldn't have to do that.
For the record, I don't think I've ever used invokeLater in the main method. It's generally not a problem until the UI is displayed.

Similar Messages

  • Using swingworker and invokeLater together

    Hi all�
    Anyone knows if there is an appropiate way to use the worker thread through SwingWorker and invokeLater together?
    It maybe sounds a bit weird but I have to launch a thread from EDT with invokeLater utility, otherwise i'd get a block state between EDT and my own thread. In other hand, I need to use SwingWorker utility for try to avoid the awful effect of loosing the visual desktop while transaction is proccesing.
    Obviously, if i use SwingWorker and inside doInBackGorund method, launch my thread with invokeLater it doesnt make any sense since the worker do its work in differents threads...
    I'd appreciate any help concerning this problem.

    Hi Albert,
    I believe that this code might help:
    /*SwinWorker Clas*/
    package swingworker;
    import javax.swing.SwingUtilities;
    * This is the 3rd version of SwingWorker (also known as
    * SwingWorker 3), an abstract class that you subclass to
    * perform GUI-related work in a dedicated thread.  For
    * instructions on using this class, see:
    * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    * Note that the API changed slightly in the 3rd version:
    * You must now invoke start() on the SwingWorker after
    * creating it.
    public abstract class SwingWorker {
        private Object value;  // see getValue(), setValue()
        private Thread thread;
         * Class to maintain reference to current worker thread
         * under separate synchronization control.
        private static class ThreadVar {
            private Thread thread;
            ThreadVar(Thread t) { thread = t; }
            synchronized Thread get() { return thread; }
            synchronized void clear() { thread = null; }
        private ThreadVar threadVar;
         * Get the value produced by the worker thread, or null if it
         * hasn't been constructed yet.
        protected synchronized Object getValue() {
            return value;
         * Set the value produced by worker thread
        private synchronized void setValue(Object x) {
            value = x;
         * Compute the value to be returned by the <code>get</code> method.
        public abstract Object construct();
         * Called on the event dispatching thread (not on the worker thread)
         * after the <code>construct</code> method has returned.
        public void finished() {
         * A new method that interrupts the worker thread.  Call this method
         * to force the worker to stop what it's doing.
        public void interrupt() {
            Thread t = threadVar.get();
            if (t != null) {
                t.interrupt();
            threadVar.clear();
         * Return the value created by the <code>construct</code> method.
         * Returns null if either the constructing thread or the current
         * thread was interrupted before a value was produced.
         * @return the value created by the <code>construct</code> method
        public Object get() {
            while (true) {
                Thread t = threadVar.get();
                if (t == null) {
                    return getValue();
                try {
                    t.join();
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // propagate
                    return null;
         * Start a thread that will call the <code>construct</code> method
         * and then exit.
        public SwingWorker() {
            final Runnable doFinished = new Runnable() {
               public void run() { finished(); }
            Runnable doConstruct = new Runnable() {
                public void run() {
                    try {
                        setValue(construct());
                    finally {
                        threadVar.clear();
                    SwingUtilities.invokeLater(doFinished);
            Thread t = new Thread(doConstruct);
            threadVar = new ThreadVar(t);
         * Start the worker thread.
        public void start() {
            Thread t = threadVar.get();
            if (t != null) {
                t.start();
    /*TestSwingWorker*/
    package swingworker;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MyApplication {
        public static void main(String[] argv) {
            final JFrame f = new JFrame("Test SwingWorker");
            /* Invoking start() on a SwingWorker causes a new Thread
             * to be created that will run the worker.construct()
             * method we've defined here.  Calls to worker.get()
             * will wait until the construct() method has returned
             * a value (see below).
            final SwingWorker worker = new SwingWorker() {
                public Object construct() {
                    return new ExpensiveDialogComponent();
            worker.start();  //new for SwingWorker 3
            /* The ActionListener below gets a component to display
             * in its message area from the worker, which constructs
             * the component in another thread.  The call to worker.get()
             * will wait if the component is still being constructed.
            ActionListener showSwingWorkerDialog = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(f, worker.get());
            JButton b = new JButton("Click here to show component constructed by SwingWorker");
            b.addActionListener(showSwingWorkerDialog);
            f.getContentPane().add(b);
            f.pack();
            f.show();
            //The following is safe because adding a listener is always safe.
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
    class ExpensiveDialogComponent extends JLabel {
        public ExpensiveDialogComponent() {
            super("This is the world's most expensive label.");
            try {
                Thread.sleep(10000); //sleep for 10 seconds
            } catch (InterruptedException e) {
    }Hope it helps!

  • Actions and events... (using code inside actionPerformed)

    Suppose I have an application that needs to be as fast as possible and have a very responsive ui. It is a client that runs against a server on the network.
    And suppose the client have a button, with an actionlistener and an actionperformed method.
    Inside this actionperformed method the client needs to send something to the server, which is basically doing something like:
    public void actionPerformed(ActionEvent e){
        doSomeWork();
        out.print(someText);
    }Where out is a PrintStream opened to the server. Now the server responds and sends a message back to the client which receives it in a network thread that runs and polls for input. When a line of input is received it is then printed to a textarea in the client gui as something like this:
    public class NetworkThread extends Thread{
    public void run() {
         byte[] b = new byte[4096];
         int n = 0;
         while (n >= 0 && connected) {
              try {
                   n = iStream.read(b);
                   String input = doSomeParsing(b, n);
                   if (input != null){
                        textArea.append(input);
    }What i would liek to know, is if it is ok to do the send call inside the actionPerformed method of the button listener and if it is ok to simply append the text to the text area in the network thread?
    Or should i use SwingUtilities.invokeLater or SwingWorker threads anywhere?
    (I would want it to run as fast as possible in the gui side)

    The code that interacts with the Server needs to be in a separate Thread so you don't block the GUI Event Thread.
    In general, if you then need to update the GUI from the second Thread you would need to use the SwingUtilities.invokeLater(..).
    However, if you read the API documentation for the JTextArea.append(...) method you will see the following:
    This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information. so you shouldn't need to worry about the invokeLater().

  • Question on SwingUtilities.invokeLater

    The program I have included is attempting to "simulate" opening and loading a file into memory.
    Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
    I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
    "Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
    Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
    1) click on Open menuItem
    2) invoke OpenAction
    3) do the "repaint" (which would cause the file menu to disappear)
    4) finish the OpenAction
    5) do the long running task
    Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestInvokeLater extends JFrame
         JFrame frame;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public TestInvokeLater()
              frame = this;
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              menuBar = new JMenuBar();
              menu = new JMenu("File");
              menuBar.add(menu);
              menuItem = new JMenuItem( new OpenAction() );
              menu.add(menuItem);
              setJMenuBar( menuBar );
              JPanel panel = new JPanel();
              panel.setPreferredSize( new Dimension( 100, 100 ) );
              setContentPane( panel );
         class OpenAction extends AbstractAction
              public OpenAction()
                   putValue( Action.NAME, "Open" );
              public void actionPerformed(ActionEvent e)
              repaint();
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              try
                   Thread.sleep(3000); // simulate log running task
              catch (Exception e) {}
         public static void main(String[] args)
              JFrame frame = new TestInvokeLater();
              frame.pack();
              frame.show();
    }

    Thanks for the input, but I still have some confusion -
    "invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
    This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
    If we assume the code for MenuItemClicked is something like:
    1) fireActionEvent
    2) fireCloseMenuEvent
    When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
    1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
    Does this make any sense?

  • Problem with threads and graphics

    I have a thread that chooses paths for a Travelling salesman problem, it then calls a TSPdraw class and passes it the path, which the class then draws. the problem is when i have two threads it creates two windows but only draws a path in one of them. any ideas where i`m going wrong

    Are you using swing components? Swing isn't threadsafe. If you have multiple threads that want to update your UI you need to use the SwingUtilities.invokeLater(...)or invokeAndWait(...). There is a page in the swing tutorial about this at: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

  • Weird Graphics2D situation encountered!!! please try to see this

    hello all! i've been doing an application which will display a window and is supposedly to paint its background with the GradientPaint method. i tried putting the method in a thread because i'm planning to display a moving text using the drawString in the future.
    i've encountered this wierd problem: there are times when the frame gets painted and there are times when it's not. it's more often that the frame isn't painted. and not all of the time when it is painted that the whole frame is filled with the GradientPaint.
    whenever the frame isn't painted "&&&&&&&&&&&&" from System.out.println("&&&&&&&&&&&&"); doesn't show up.
    here's my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.border.*;
    import java.awt.geom.*;
    public class Test implements ActionListener {
    public static void main(String[] args) {
    f = new TestFrame();
    f.show();
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
         FlowLayout fl = new FlowLayout(0,30,30);
    jd.setBounds(400,250,300,200);
    jd.setResizable(false);
    jd.getContentPane().setLayout(new FlowLayout(0,30,30));
    l.setFont(new Font("Serif", Font.PLAIN, 18));
    l.setLocation(0,0);
    l.setFocusable(false);
    jd.getContentPane().add(l);
         yes.setPreferredSize(new Dimension(100,50));
    yes.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    yes.setFont(new Font("Serif", Font.PLAIN, 18));
    yes.addKeyListener(new KeyHandler());
    yes.addActionListener(mp);
    InputMap map = yes.getInputMap();
    if (map != null){
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
    jd.getContentPane().add(yes);
    no.setPreferredSize(new Dimension(100,50));
    no.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    no.setFont(new Font("Serif", Font.PLAIN, 18));
    no.addKeyListener(new KeyHandler());
    no.addActionListener(mp);
    InputMap map1 = no.getInputMap();
    if (map1 != null){
    map1.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
    map1.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
    jd.getContentPane().add(no);
         jd.show();
    public void actionPerformed(ActionEvent e) {
    String bname = e.getActionCommand();
    if(bname=="Yes") {
    System.exit(0);
    jd.dispose();
    static class KeyHandler extends KeyAdapter {
    public void keyReleased(KeyEvent e) {     
    int keycode = e.getKeyCode();
    if(keycode==10 && yes.hasFocus()==true) {
    System.exit(0);
    static JFrame f;
    static Test t = new Test();
    static JDialog jd = new JDialog(f,"TEST");
    static JLabel l = new JLabel("Would you like to close TEST?");
    static JButton yes = new JButton("Yes");
    static JButton no = new JButton("No");
    class TestFrame extends JFrame {
    public TestFrame() {
    setBounds(wndSize.width/4,wndSize.height/4,wndSize.width/2,wndSize.height/2);
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    setResizable(false);
    setTitle("test");
    canvas = new JPanel();
    getContentPane().add(canvas, "Center");
    MoveThread mt = new MoveThread(canvas);
    mt.start();
    Toolkit theKit = getToolkit();
    Dimension wndSize = theKit.getScreenSize();
    Area area = new Area(new Rectangle2D.Double(0,0,510,345));
    private JPanel canvas;
    class MoveThread extends Thread {
    public MoveThread(JPanel canvas) {
    c = canvas;
    public void paintComponent() {
    Graphics2D g2 = (Graphics2D)c.getGraphics();
    g2.setPaint(new GradientPaint(0,0,Color.green,510,345,Color.white));
    System.out.println("&&&&&&&&&&&&");
    g2.fill(area);
    g2.dispose();
    public void run() {
    try {
    paintComponent();
    sleep(5);
    } catch(Exception e) { }
    private JPanel c = new JPanel();
    Area area = new Area(new Rectangle2D.Double(0,0,510,345));
    thanks for taking some time to look at this problem!
    cheers, deo

    Hi,
    First, if you expect your paintComponent() method to get called by Swing then it should have a Graphics argument.
    Second, it is normally a bad idea to get a Graphics from a component. You should use the one provided by the paintComponent() method.
    Third, it is normally a bad idea to update anything in the GUI in a separate thread. Update your model but use the SwingUtilities.invokeLater() function to update your view of the data.
    Forth, consider double buffering - draw your graphics onto an image and then use the paintComponent(Graphics g) to paint the image to the display.
    Roger

  • What's a good way to prompt a user with an error message etc. in swing?

    i want to be able to prompt the user within a given a function that i've created .. with some kind of warning message or error message .. or anything for that matter ..
    is there even a timer of some sort that i could use for the prompt .. say if im connecting and i want to prompt the user with a 'connecting ... ' message .. then close it when ive secured the connection? ...
    simple aesthetics i guess .. but a want indeed.

    For your first question, just use the static JOptionPane.showXXX methods.
    If you are making a connection in another thread, use the SwingUtilities.invokeLater (or in this case even invokeAndWait) method to close the dialog from the other thread.

  • Problem seeing a jframe components

    Hello,
    My problem is this. I have a main jframe. Now on my main jframe i have to do a time expensive procedure called refresh(); While this procedure is running i want to display a message in a JWindow that says "Please wait". Problem is that no matter what the JWindow object won't show its components until the procedure refresh is done. That means of course that my JWindow is pointless.
    So I tried with swingworker to create a thread that runs the procedure refresh(). But that doesn't seem to work.
    final please_wait ff= new please_wait();//this is my JWindow
    final SwingWorker worker = new SwingWorker() {
    public Object construct() {
    Runnable doWorkRunnable = new Runnable() {
    public void run() {   refresh();//this is the time consumming procedure }
    SwingUtilities.invokeLater(doWorkRunnable);
    return "s"; //return value not used by this program
    //Runs on the event-dispatching thread.
    public void finished() {
    ff.dispose(); ///here i destroy the JWindow because the time consuming procedure is over
    worker.start();

    I believe you have misunderstood the use of the invokeLater() method. It isn't used to execute time consuming tasks. You would use invokeLater() to put a GUI operation on the event dispatcher thread from a thread you have spawned off to execute outside of the event dispather thread i.e. from the thread you will use to execute your time consuming task (Since all GUI operations should be executed from the event dispatcher thread).
    Your steps of actions here would be (assuming what ever kicks off your time consuming task happens from an event listener...like a button press):
    1) Construct and display our JWindow
    2) Spawn a new thread with your time consuming task in it.
    3) When your time consuming task is done remove your JWindow by putting a call to its dispose() method in a Runnable object which you pass to SwingUtilities.invokeLater(Runnable).
    You can replace steps 2 and 3 with SwingWorker if you prefer (and it appears you do) since it encapulates this functionality. SwingWorker's finished method is where you would dispose of your JWindow and since the operations in the finished method are already executed on the event dispather thread you don't need to worry about invokeLater.

  • Program Freezes when setting up GUI & can't figure why...

    Hi Folks,
    I'm having some serious problems with a program i've written, basically the program creates several threads.
    Each thread creates and uses a JFrame to play a movie.
    The problem i'm getting though is that the program keeps freezing(deadlocking) on me when i'm in the process of setting up each JFrame. I haven't even started the threads....
    This happens intermittedly too boot, what i mean is that the program could run all day, then when it tries to setup a new group of JFrames will freeze, or it could run for just one hour and then the same would happen. I don't know why it is happening... Below is all the relevant code.
    //code from the class which creates the Threads (the threads are called polly and passes the details
    // required to them
    private void createAndSendPollyDetails(){
            for(int i = 0; i < polly.length; i++){
                polly[i] = new Polly(basil);
                System.err.println(" created polly: " + (i+1));
                //get screen percentages
                for(int w = 0; w < 4; w++) {
                    if (w == 0){
                        sWidth = screenSizePercentages[i][w];
                    if (w == 1){
                        eWidth = screenSizePercentages[i][w];
                    if (w == 2){
                        sHeight = screenSizePercentages[i][w];
                    if (w == 3){
                        eHeight = screenSizePercentages[i][w];
                System.err.println("about to send setupScreen details");
                polly.setUpScreen(sWidth,eWidth,sHeight,eHeight);
    System.err.println("about to send array data");
    polly[i].setVals(AScreenDisplayDataHolder.getPlayList(i),
    AScreenDisplayDataHolder.getPlayListLengths(i),
    AScreenDisplayDataHolder.getSizeOfPlayList(i),
    AScreenDisplayDataHolder.getSizeOfPlayListLengths(i));
    if(AScreenDisplayDataHolder.getMainScreenInMainScreenDetails(i)) {
    boolean b = true;
    mainPollyNumber = i;
    polly[i].setMainTrue(b);
    polly[i].setMainLen(AScreenDisplayDataHolder.getMainLengthInMainScreenDetails(i));
    try{
    Thread.sleep(1300);
    }catch (InterruptedException ie) {
    ie.printStackTrace();
    // code from Thread, which just sends the details to screen for setup, the threads haven't even started....
    public void setUpScreen(final double sWidthIn, final double eWidthIn, final double sHeightIn, final double eHeightIn) {
    System.err.println("calling screen.setDisplay");
    Runnable doWorkRunnable = new Runnable() {
    public void run() { screen.setDisplay(sWidthIn, eWidthIn, sHeightIn, eHeightIn);  }
    //SwingUtilities.invokeLater(doWorkRunnable);
    try{
    SwingUtilities.invokeAndWait(doWorkRunnable);
    } catch(InterruptedException ie) {
    System.err.println("error");
    } catch(InvocationTargetException ite) {
    System.err.println("target exception");
    System.err.println("fin call to screen.setDisplay");
    public void setVals(final String[] movieArrayIn, final String[] movieLengthArrayIn, final int lengthOfMovieArray,
    final int lengthOfMovieLengthArray) {
    Runnable doWorkRunnable = new Runnable() {
    public void run() { screen.setValues(movieArrayIn, movieLengthArrayIn, lengthOfMovieArray, lengthOfMovieLengthArray);
    System.err.println("screen.setValues has finished in the void run method");
    //SwingUtilities.invokeLater(doWorkRunnable);
    try{
    SwingUtilities.invokeAndWait(doWorkRunnable);
    } catch(InterruptedException ie) {
    System.err.println("error");
    } catch(InvocationTargetException ite) {
    System.err.println("target exception");
    System.err.println("got to end of SetVals");
    //code from the JFrame which loads the data required by the JFrame into arrays and sets the size(bounds)
    // of the JFrame. Had to use setBounds as start location not always going to be 0,0 for all JFrames
    public void setValues(final String[] movieArrayIn, final String[] movieLengthArrayIn, final int lengthOfMovieArray,
    final int lengthOfMovieLengthArray) {
    Runnable doWorkRunnable = new Runnable() {
    public void run() {
    movieArray = new String[lengthOfMovieArray];
    System.err.println("done moviearray new");
    movieArray = movieArrayIn;
    System.err.println("done moviearray copy");
    movieLengthArray = new String[lengthOfMovieLengthArray];
    System.err.println("done movieaLengthArray new");
    movieLengthArray = movieLengthArrayIn;
    System.err.println("done movieLengthArray Copy");
    SwingUtilities.invokeLater(doWorkRunnable);
    // set the size of the screen
    public void setDisplay(final double sWidthIn, final double eWidthIn, final double sHeightIn, final double eHeightIn){
    Runnable doWorkRunnable = new Runnable() {
    public void run() {
    Dimension wholeScreenSize = getToolkit().getScreenSize();
    if(sWidthIn == 0){
    sWidth = 0;
    else {
    sWidth = wholeScreenSize.getWidth()/100 * sWidthIn;
    if(eWidthIn == 0){
    eWidth = 0;
    else {
    eWidth = (wholeScreenSize.getWidth()/100 * eWidthIn) - sWidth;
    if(sHeightIn == 0){
    sHeight = 0;
    else {
    sHeight = wholeScreenSize.getHeight()/100 * sHeightIn;
    if(eHeightIn == 0){
    eHeight = 0;
    else {
    eHeight = (wholeScreenSize.getHeight()/100 * eHeightIn) - sHeight;
    Screen.this.setBounds((int)sWidth, (int)sHeight, (int)eWidth, (int)eHeight);
    System.err.println("done SetBounds");
    screenSize = new Dimension((int)eWidth,(int)eHeight);
    System.err.println("done setting dimension screenSize");}
    SwingUtilities.invokeLater(doWorkRunnable);
    As you can see i've tried putting them all in SwingUtilities.invokeLater, and still freezes....
    I don't understand why it still does freeze... I'm also wondering when do you need to use the SwingUtilities.invokeLater and invokeAndWati, is it when you are changing/using any element/variable within a JFrame or just when you are changing/using and element/variable that effects the GUI display on a screen
    Please help,
    I'm very stuck,
    Andy.

    Keep it simple, start by removing all of the threads launches and frame builds and make sure it runs. Then have it build one frame and one thread and see if it runds. Then add another one and then ... you get the idea.
    The first thought I had when I was reading your post was that you might want the thread to spin up its own frame rather than have the frame done first and then the thread launched.
    Just a couple of thoughts on the subject.

  • Swing Threads

    Does anybody know how the threads in a swing application are organized. I noticed, that when i start a swing application more then 10 threads are created. Furthermore, when the "main" thread is terminated after showing the main window (a JFrame window), two windows are displayed. When the main-thread is ran in a loop (while (true) {try{Thread.sleep(100);}catch(Exception x){}), only one window is displayed. So, even if the main thread does nothing, it's necessary.
    Furthermore, i realized that, when starting other threads out from the main thread, on some win 2000 systems the threads are properly terminated but the associated handles are not freed - this leads to a "handle leak" after a certain time (48 hours). If the threads are started with invokeLater out from the main thread, then the handles are freed properly when the thread terminates.
    Does anybody know how these facts can be put together to get a bigger whole ?
    Thanks a lot.
    Stephan Gloor
    Switzerland

    hi,
    the rule is:
    swing components are not thread-safe except some, and therefore they should only be changed from within the event dispatch thread. this can be accomplished using the methods invokeLater(Runnable) and invokeAndWait(Runnable) in class javax.swing.SwingUtilities.
    best regards, Michael

  • Events,firing,listening-GUI/Networking seperation.

    I'm having a little trouble finding info on how to write my own events, event listeners and then how to fire these events. Basically i want to listen on a socket for info and then fire an event. I want to have a JList listen for this event and update itself.
    I'm not sure if this is the best way to do it but I'd really be interested in any ideas or pointers to info on other ways this could be done.
    Cheers.
    -T

    1. By default, reading from a socket blocks, so the simplest thing to do is start a thread to do the reading. (I haven't checked the i/o facility for polling in 1.4, but that would help if you were listening to several sockets).
    2. Once you read some data, you need to update your ListModel. If you're using DefaultListModel, you're laughing because it manages its listener list and fires off events for you. But see point 4.
    3. If you are subclassing AbstractListModel, you would need to call the appropriate fire*() method whenever your model changes state.
    4. Watch out for Swing and threads. Listeners assume their being called in the EDT (Event Dispatch Thread). Typically, this means your socket reading thread uses SwingUtilities method invokeLater().
    --Nax

  • TextPANE's Y_AXIS preferredSpan not set, but textAREA's is ?

    I can do
    area = new JTextArea();
    area.setText( "Some text" );
    view = area.getUI().getRootView( area );
    height = view.getPreferredSpan( View.Y_AXIS ) ;and height is set to 16.0. But if I do
    pane = new JTextPane();
    pane.setText( "Some text" );
    view = pane.getUI().getRootView( pane );
    height = view.getPreferredSpan( View.Y_AXIS );height is always 0.0. Why is this?
    Interestingly,
    width = view.getPreferredSpan( View.X_AXIS );does give me a value back , the same in both cases ( 54.0 in my case ).
    : jay

    Why is this?Check out this demo code:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class UTextComponent
         **  Return the current column number at the Caret Position.
         public static int getColumnAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              int line = root.getElementIndex( caretPosition );
              int lineStart = root.getElement( line ).getStartOffset();
              return caretPosition - lineStart + 1;
              int rowStart = 0;
              try
                   rowStart = Utilities.getRowStart(component, component.getCaretPosition());
              catch(BadLocationException ble) {}
              return component.getCaretPosition() - rowStart;
         **  Return the current line number at the Caret position.
         public static int getLineAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementIndex( caretPosition ) + 1;
         **  Return the number of lines of text.
         public static int getLines(JTextComponent component)
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementCount();
         **  Position the caret at the start of a line.
         public static void gotoLine(JTextComponent component, int line)
              Element root = component.getDocument().getDefaultRootElement();
              line = Math.max(line, 1);
              line = Math.min(line, root.getElementCount());
              component.setCaretPosition( root.getElement( line - 1 ).getStartOffset() );
              //  The following will position the caret at the start of the first word
              try
                   component.setCaretPosition(
                        Utilities.getNextWord(component, component.getCaretPosition()));
              catch(Exception e) {System.out.println(e);}
         **  Return the number of lines of text, including wrapped lines.
         public static int getWrappedLines(JTextPane component)
              int lines = 0;
              View view = component.getUI().getRootView(component).getView(0);
              System.out.println("view: " + (int)view.getPreferredSpan(View.Y_AXIS) );
              int paragraphs = view.getViewCount();
              System.err.println("p: " + paragraphs);
              for (int i = 0; i < paragraphs; i++)
                   lines += view.getView(i).getViewCount();
              return lines;
         **  Return the number of lines of text, including wrapped lines.
         public static int getWrappedLines(JTextArea component)
              View view = component.getUI().getRootView(component).getView(0);
              int preferredHeight = (int)view.getPreferredSpan(View.Y_AXIS);
              int lineHeight = component.getFontMetrics( component.getFont() ).getHeight();
              return preferredHeight / lineHeight;
         public static void main(String[] args)
              final JTextPane textComponent = new JTextPane();
    //          final JTextArea textComponent = new JTextArea(5, 15);
    //          textComponent.setLineWrap( true );
    //          textComponent.setWrapStyleWord( true );
    //          textComponent.setText("1\n2\n3\n4\n5\n6\n7");
    //          textComponent.setEditable(false);
              textComponent.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        System.out.print
                             "Column/Line : " +
                             UTextComponent.getColumnAtCaret( textComponent ) +
                             "/" +
                             UTextComponent.getLineAtCaret( textComponent ) +
                             ", Lines : " +
                             UTextComponent.getLines( textComponent ) +
                             ", Wrapped Lines : "
                        //  It looks like the View has not yet been updated.
                        //  Add request to end of queue
    //                    SwingUtilities.invokeLater( new Runnable()
    //                         public void run()
                                  System.out.println(
                                       UTextComponent.getWrappedLines( textComponent ) );
              JScrollPane scrollPane = new JScrollPane( textComponent );
              JPanel panel = new JPanel();
              panel.add( new JLabel( "Goto Line:" ) );
              final JTextField gotoField = new JTextField(4);
              panel.add( gotoField );
              gotoField.addActionListener( new java.awt.event.ActionListener()
                   public void actionPerformed(java.awt.event.ActionEvent e)
                        UTextComponent.gotoLine(textComponent,
                             Integer.parseInt( gotoField.getText()) );
                        gotoField.setText("");
                        textComponent.requestFocus();
              JFrame frame = new JFrame( "Text Component Utilities" );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( scrollPane );
              frame.getContentPane().add(panel, java.awt.BorderLayout.SOUTH);
    //          frame.pack();
              frame.setSize(300, 300);
              frame.setVisible(true);
    }a) Run the code as is
    b) enter a single character, view = 16
    c) use enter key to add a new line, view = 16
    d) use enter key to add a new line, view = 32
    This is inconsistent behaviour. The view should change with each new line
    e) use backspace key until you are left with a single character, view = 0 ?
    f) use left arrow key, view = 16
    Again this is inconsistent
    Now remove the comments for the code that uses the SwingUtilities.invokeLater and repeat above tests. This view seems to update normally as far as I can see.
    So, I guess the answer to your question is that the view processing for JTextPane is more complicated than it is for JTextArea and some of this processing is added to the end of the event thread when the setText() method is used, so you are getting an old value.
    Also, notice how my two methods for getWrappedLines are different for the JTextArea and JTextpane. You would hope/expect that the view methods would return the same values but they didn't. In this case I would consider the JTextPane to be the correct code and the JTextArea inconsistent.

  • SQL query / thread problem!

    I have the following code. when the execute mkethod is called, an instance of TransactionRunner is created. within the run method of TransactionRunner an SQLQuery is executed. I want to return the result set when the query has been executed, how can I do this, at the moment it tries to return the resultSet before the thread has finished. any ideas? I hav tried using a boolean as a flag but it doesn't appear to work.
    public static ResultSet execute(String SQL, boolean rs)
    System.out.println("in execute, dbm") ;
    SQLStatement = SQL ;
    result = rs ;
    complete = false ;
    tr = dbm.new TransactionRunner(SQL) ;
    //SOME FORM OF INDICATION TO THE END OF SQL EXECUTION
    return resultSet ;
    class TransactionRunner implements Runnable
         public ResultSet rs ;
         private Thread queryThread ;
         public String SQLStatement ;
         public TransactionRunner(String SQL)
              SQLStatement = SQL ;
              queryThread = new Thread(this) ;
              queryThread.start() ;
         public void run()
              if (result == true)
                   executeQuery(SQLStatement) ;
                   complete = true;
              else
                   update(SQLStatement) ;
              }

    I am up against the same problem, but I believe that
    you could fire off a progress monitor during the
    thread task and have the thread return the ResultSet.If you're planning to use Swing, then yes, you do need to execute the command in a spawned thread, otherwise your event thread will hang. BUT, spawning a sub-thread from a Swing app is not equivalent to spawning one from a simple console app, because the Swing event thread will keep your process alive. Instead, I would suggest doing something like the following:
    1) In the ActionListener that invokes the query (may be hung off a menu item, or a button, depending on your app):
            public void actionPerformed(ActionEvent actionEvent)
                (new Thread(new MyQuery())).start();
                displayWaitIndication();
            }This method runs in the event thread, and spawns a sub-thread to run the query. It also displays some sort of wait indication, maybe a progress box or a WAIT_CURSOR (I prefer the wait cursor, as you can't accurately display the progress of a server-side operation).
    2) MyQuery implements Runnable:
            public void run()
                List data = // call something to perform DB op here
                SwingUtilities.invokeLater(new Runnable()
                    public void run()
                        mainWindow.refresh(data);
            }This may be a bit confusing, as it leaves a lot of stuff out. I've used "List" as the return from the database function; chances are that you'll actually implement something like MyResultSet. You don't want to use an actual java.sql.ResultSet, because it (may) perform(s) a client-server call to retrieve each row. So, you process the real result-set into a container object (List or whatever) in the sub-thread.
    Then, you pass that container object back to the display window, on the event thread. I've used a variable to access the display window; you may do things differently. The key thing is the use of SwingUtilities.invokeLater(), to perform the actual update on the event thread.
    To summarize:
    1) You initiate the action on the event-thread.
    2) You perform the action in a sub-thread, put the resuls into a container.
    3) You update your display on the event-thread, using SwingUtilities.invokeLater().

  • Handling Enter key event in JTable

    Hi...
    This is particularly for the user "VIRAVAN"...
    I have followed your method ,and got results too.. but the
    processKeyBinding(.. method is called 4 times,same problem addressed by you before, but I didn't understood it...
    Please help me...
    Here is my code...
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed)
    System.out.println("Wait");
    if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))
    int selRow = getSelectedRow();
    int rowCount = getRowCount();
    int selCol = getSelectedColumn();
    String val =(String)getValueAt(selRow,selCol);
    boolean b= getCellEditor(selRow,selCol).stopCellEditing();
    System.out.println(b);
    System.out.println(rowCount-1 + " "+ selRow + " " + getSelectedColumn());
    if((!val.equals("")) && selRow==rowCount-1)
    System.out.println(rowCount-1 + " "+ getSelectedRow()+ " " + getSelectedColumn());
    blank1 = new String[columns];
    for(int p=0;p<columns;p++)
    blank1[p]="";
    Diary.this.datarows.addElement(blank1);
    // dataModel.fireTableStructureChanged();
    //dataModel.fireTableDataChanged();
    Diary.this.dataModel.fireTableChanged(null);
    else if(ks ==KeyStroke.getKeyStroke(KeyEvent.VK_1,0))
    System.out.println("One One One One ");
    return super.processKeyBinding(ks,e,condition,pressed);

    It's been a while since I looked at the code, but essentially there are three key event types:
    1) key pressed,
    2) key typed,
    3) key released.
    So I would expect the processKeyBind to see all three of them. However, ks==KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) is true only when a key typed event is detected (the other types can be ignored by passing it up the food chain where they will eventually be consumed). Now...., if I understand you correctly, you want to terminate edit on the present of Enter key, right? Here is how I'd suggest you do:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }Ok.... now, it appears that you want to do something else also... i.e., add a new row to the table if the editing row is the last row and the editing column is the last column of the last row. You can't do that in the same thread (i.e., you must wait until the update in the current thread is completed). So, what you must do is use the SwingUtilities.InvokeLater, like this:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             if (getEditingRow()+1==getRowCount() && getEditingColumn()+1==getColumnCount()) {
                SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
    // put the code for adding new row here
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }OK?
    ;o)
    V.V.
    PS: posted code is untest but should work!

  • Handler

    Hello
    I have tow JscrollPane ,J1 and J2 and I want that when J1 up or down his scrollBar j2 up or down too.
    I have make a handler for J1 that when there is a event of scroll pane this move the scrollbar of J2,good, but this produce exceptions and the code isn't correct execute.
    must i use the class invokelater?
    how can I use the class invokelater in a handler?
    Thanks a lot and I'm sorry for my bad english.
    Jose

    I wonder if this is documented behavior, or just a side-effect that happens to work.This is the whole point of the MVC design. The model stores the data and notifies the view when something changes. That way you can have different views of the same model.
    In the case of a ScrollBarModel as long as the size of the scrollbar is the same you shouldn't have a problem.
    You can even share models across different components. For example a ListSelectionModel could be shared by a JTable and a JList, again you would want to keep the number of elements in each model the same. So you might consider that requirement a gotcha.
    Models might also be shared when you want the same component to appear on multiple panels. This is not possible as a component can only have a single parent. However, you can easily create multiple components that share the same model and add each component to a different panel.

Maybe you are looking for

  • Xbox 360 and 360 connect using mini.. please help

    My setup is I have my internet running through a Dlink di-524 router which is wired to my Macmini. I have xbox 360 in the other room connected via cable to a gigafast wireless router. Im basically using this gigafast router as an alternative to the e

  • Item data in smartform

    hi, in my main window i am having 5 columns. out of which one column contains the item datas like: for one delivery order in second column it should have: description (code no) no  of packs type of material. for this should i create 4 text elements?

  • How to replace title bar from image

    Respected Sir/Madem, please help me, how we replace title bar of farme from image.and also that image have button like minimiz,restore,and close. i want to completely replace my title bar to a image for example NeoPlanet browser. plz givehelp.

  • HT3406 how to backup text messages?

    I read that text messages can be backed up but no place do I see an option to do this. How can I backup and then restore all text and imessages?

  • Can't re-install after uninstall

    I was told by the developer of an App Store app to uninstall + re-install his app, iNet.  After uninstalling + re-starting, my App Store shows that the app is installed, even though it's not listed in my Applications.  How can I re-install?