JavaFX binding throws illegal state Exception: not on the thread of Application FX

Hi all

I am updating a label of a task using bindings.

However, when I 'Bind' the label text property with a property of the task, Illegal state exception string is thrown. Saying: this is not not on the thread of JavaFX.

The Exception occurs whenever I try to set the property of the task of the Interior string.

Please do not suggest to use the platform. RunLater(). I want to do this through links as the values I am trying to display in the label (later on) could change too frequently, and I don't want to flood the queue of the thread of the user interface with executable objects.

Please let me know what I'm doing wrong and what I need to change to make it work properly with links. (I'm new to links and concurrency JavaFx API)

Here is my Code.

public class MyTask extends Task<String>{

    MyTask(){
       System.out.println("Task Constructor on Thread "+Thread.currentThread().getName());


    }
    private StringProperty myStringProperty = new SimpleStringProperty(){
        {
            System.out.println("Creating stringProperty on Thread "+Thread.currentThread().getName());
        }
    };
    private final void setFileString(String value) {
        System.out.println("Setting On Thread"+Thread.currentThread().getName());
        myStringProperty.set(value); }
    public final String getFileString() { return myStringProperty.get(); }
    public final StringProperty fileStringProperty() {
        System.out.println("Fetching property On Thread"+Thread.currentThread().getName());
        return myStringProperty; }
    
    @Override
    public String call() throws Exception{
        System.out.println("Task Called on thread "+Thread.currentThread().getName());


       for(int counter=0;counter<100;counter++){
           try{
           setFileString(""+counter);
           }catch(Exception e){
               e.printStackTrace();
           }
           Thread.sleep(100);
           System.out.println("Counter "+counter);
       }
       return "COMPLETED";
    }
}


public class MyService extends Service<String> {


    MyTask myTask;

    public MyService(){
        System.out.println("Service Constructor on Thread "+Thread.currentThread().getName());
        myTask=new MyTask();
    }

    @Override
    public Task createTask(){
        System.out.println("Creating task on Thread "+Thread.currentThread().getName());
        return myTask;
    }

}


public class ServiceAndTaskExperiment extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}


public class SampleController implements Initializable {
    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        myTestService.start(); //This will throw out exceptions when the button is clicked again, it does not matter
    }

    MyService myTestService=new MyService();
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        label.setText("Hello World!");
        //adding the below Line causes the exception
        label.textProperty().bind(myTestService.myTask.fileStringProperty()); //removing this line removes the exception, ofcourse the label wont update.
    } 
}
//sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>


<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="serviceandtaskexperiment.SampleController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>



And it is the output with links on:

Output: when the link is activated label.textProperty () .bind (myTestService.myTask.fileStringProperty ());

Service on JavaFX Application Thread constructor

Creating string on thread JavaFX Application Thread

Task, Builder on JavaFX Application Thread

Get the property on request ThreadJavaFX wire

You clicked me!

Creating a task on a thread Thread Application JavaFX

Task called threadThread-4

Setting on ThreadThread-4

java.lang.IllegalStateException: not on the application thread FX; currentThread = Thread-4

at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:237)

at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:398)

to javafx.scene.Parent$ 1.onProposedChange(Parent.java:245)

at com.sun.javafx.collections.VetoableObservableList.setAll(VetoableObservableList.java:90)

at com.sun.javafx.collections.ObservableListWrapper.setAll(ObservableListWrapper.java:314)

at com.sun.javafx.scene.control.skin.LabeledSkinBase.updateChildren(LabeledSkinBase.java:602)

at com.sun.javafx.scene.control.skin.LabeledSkinBase.handleControlPropertyChanged(LabeledSkinBase.java:209)

to com.sun.javafx.scene.control.skin.SkinBase$ 3.changed(SkinBase.java:282)

at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:107)

to com.sun.javafx.binding.ExpressionHelper$ SingleChange.fireValueChangedEvent (ExpressionHelper.java:196)

at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)

at javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:121)

at javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:128)

in javafx.beans.property.StringPropertyBase.access$ 100 (StringPropertyBase.java:67)

to javafx.beans.property.StringPropertyBase$ Listener.invalidated (StringPropertyBase.java:236)

to com.sun.javafx.binding.ExpressionHelper$ SingleInvalidation.fireValueChangedEvent (ExpressionHelper.java:155)

at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)

at javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:121)

at javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:128)

at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:161)

at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:67)

to serviceandtaskexperiment. MyTask.setFileString (MyTask.java:24)

to serviceandtaskexperiment. MyTask.call (MyTask.java:36)

to serviceandtaskexperiment. MyTask.call (MyTask.java:11)

to javafx.concurrent.Task$ TaskCallable.call (Task.java:1259)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

to java.util.concurrent.ThreadPoolExecutor$ Worker.run (ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:724)

Output with links removed: (label will not be updated)

Service on JavaFX Application Thread constructor

Creating string on thread JavaFX Application Thread

Task, Builder on JavaFX Application Thread

You clicked me!

Creating a task on a thread Thread Application JavaFX

Task called threadThread-4

Setting on ThreadThread-4

Counter 0

Setting on ThreadThread-4

1 meter

Setting on ThreadThread-4

2 meter

Setting on ThreadThread-4

If myStringProperty is bound to the textProperty of etiquette, you can only change it on the Thread of the JavaFX Application. The reason is that change its value will result in a change of the label, and changes of live parts of the graphic scene cannot be performed on the Thread of the JavaFX Application.

Task and Service classes expose a messageProperty you could use here. The Task class has a updateMessage (...) method that changes the value of the message on the Thread of the JavaFX Application property. It also merges calls in order to prevent the flooding of this thread. If you could do the following in your MyTask.call () method:

updateMessage(""+counter);

and then in your controller just do

label.textProperty().bind(myTestService.messageProperty());

If you don't want to use the messageProperty for some reason any (for example you are already using it for something else, or you want to make something similar to a property that is not a string), you must merge the updates yourself. What follows is based on the source code of the task:

public class MyTask extends Task {

     // add in the following:
    private final AtomicReference fileString = new AtomicReference<>();

    private void updateFileString(String text) {
        if (Platform.isFxApplicationThread()) {
            setFileString(text);
        } else {
            if (fileString.getAndSet(text) == null) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        final String text = fileString.getAndSet(null);
                        MyTask.this.setFileString(text);
                    }
                });
            }
        }
    }

   // Now just call updateFileString(...) from your call() method
}

Tags: Java

Similar Questions

  • Illegal state Exception when running the code at startup

    Here's my main method:

        public static void main(String[] args)
        {
            if (args.length == 1 && args[0].equals("startup"))
            {
                Criteria locationCriteria = new Criteria();
                locationCriteria.setCostAllowed(false);
                LocationProvider mlocationProvider;
                Location mLocation = null;
                try
                {
                    mlocationProvider = LocationProvider
                            .getInstance(locationCriteria);
                    mLocation = mlocationProvider.getLocation(-1);
                }
                catch (LocationException e) {
                }
                catch (InterruptedException e) {
                }
                QualifiedCoordinates mQC = mLocation.getQualifiedCoordinates();
            }
            else
            {
                MyApp theApp = new MyApp();
                theApp.enterEventDispatcher();
            }
        }
    

    The method

     mlocationProvider = LocationProvider.getInstance(locationCriteria); 
    

    throws the illegal state exception

    When I check the debug information, I found this exception are thrown to the line when he calls Application.getApplication ();

    When I move this code to run in a normal life to screen it works fine. !

    Any help?

    There may be a number of issues here:

    (1) until your Application is actually running, you can't really do any processing.  Your Application does not start running until you

    'enterEventDispatcher() '.

    Hand, all you should do is instantiate your Application.  Manufacturer of your Application should not do anything complicated either, since it works as part of main().

    You can do some activities, for example to add listeners, in main() code that is, in some respects, unfortunate because it lulls people into thinking they can do anything.  ,

    (2) get the location as you do, is a blocking call.  If you need to do it on a background Thread.  You c a get away with that on the Simulator because GPS simulated returns immediately with a location.  So it does not actually block.  But on a real device, code as you can force your application to break.

    (3) you seem to try to do something in the commissioning.  You must be aware, this start-up up is called as part of the start-up of the device and before the unit is fully active.  In fact, I think on a real device that this code will fail because the device is not ready to provide a location in the beginning upward.

    You will find find article, informative and useful for (1) and (3).

    http://supportforums.BlackBerry.com/T5/Java-development/write-safe-initialization-code/Ta-p/444795

    I suspect you want to start and get a location at first upward, in which case you might find this useful:

    http://supportforums.BlackBerry.com/T5/Java-development/create-a-background-application/Ta-p/445226

  • By clicking on the button "return" gives illegal state exception

    Hello

    In my app, when I'm clicking on I show a dialog box. and when I am pressing Yes in the dialog box, it gives me the illegal state exception. But I want to return to the previous screen. If I'm clicking on menu and then clicking Close, and then it goes back to the previous screen. Here is my code:

    public boolean keyDown(int keycode, int time) {
    
            if (Keypad.KEY_ESCAPE == Keypad.key(keycode)) {
                int result = Dialog.ask(Dialog.D_YES_NO, "Do you want to edit the list?");
                if (result == Dialog.YES)
                {
                    try
                    {
                        UiApplication.getUiApplication().popScreen(this);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
    //              onClose();
                }
                else
                {
                    return true;
                }
            } // end if
    
            return false;
        }
    

    Please help me...

    Same question in StackOverFlow:

    Dear arindamhit,

    When you are clicking back into the device and then by default button the onclose() method is called. So try to do like this;

    protected boolean onSavePrompt()
    {
        return true;
    }
    
    public boolean onClose()
    {
        int choose=Dialog.ask(Dialog.D_YES_NO, "Close the screen");
        if(choose==Dialog.YES)
        {
            return super.onClose();
        }
        return true;
    }
    

    It's the best way; If you use like the one above you might get a problem; It is:

    *) If you use this method on the first screen, then according to your code when popup screen then there is no screen in the battery display (because it's the first screen); So you could get this kind of problem;

    Try this one;

  • Menu rollover State does not have the button active parent

    My menu rollover State does not work the button parent in my menu while I'm on a page of the child. I didn't have any currently active States in the menu. How can I get the parent menu to respect the rollover State even while I'm on one of the child pages?

    Please check this thread:

    https://forums.Adobe.com/message/6148234#6148234

    Thank you

    Sanjit

  • I'm not able to get the email to sort properly... not on the threads.

    No matter what I do the emails do not sort by date received, without rhyme or reason troubled crazy!

    So are you sure that's not on the threads?
    Go to View-sort by and tell me what are the 3 elements have markers next to them.

  • see URLEncodedPostData.getBytes () and illegal state Exception

    Hi, expert,

    recently when I tried to understand the device encryption, I discovered my starts http grave failed when the device is locked and the encryption is enabled. After the addition of debugging information more, I finally discovered that the exception is thrown to the URLEncodedPostData.getBytes () with IllegalStateException, here is a part of the stack trace:

      IllegalStateException
        No detail message
        net_rim_cldc-11(4DE8751A)
         PersistentContent
         decode
         0x8E80
        net_rim_cldc-11(4DE8751A)
         PersistentContent
         decode
         0xB1FC
        net_rim_cldc-11(4DE8751A)
         PersistentContent
         decode
         0xB18A
        net_rim_bb_browser_lib(4DE8802C)
         URLEncodedFormData
         toString
         0xB6C9
        net_rim_bb_browser_lib(4DE8802C)
         URLEncodedFormData
         getBytes
         0xB6B2
        net_rim_bbapi_browser(4DE88041)
         URLEncodedPostData
         getBytes
         0x411
    

    Then I did some search on the forum, I found this link, and that is exactly the same as what I saw: http://supportforums.blackberry.com/t5/Java-Development/URLEncodedPostData-getBytes-and-Illegal-Stat... As I saw no explanation on this thread, I just open this post to see if there is any explanation about it.  I guess that fi that we can't work around this problem, we would have to write code ourselves url code.

    This proximity. Work of my own URL encoding code which is pretty easy to code.

  • Stage of JavaFX Builder 1.0 error: could not create the Virtual Machine Java.

    Hello
    I have installed JavaFX scene Builder under Windows 7 x 32. The installation process is OK, but when I try to launch the app it crashes and displays an error that says:
    "Error: could not create the Virtual Machine Java.".
    Error: A fatal error has occurred. Program will exit. »

    I installed JVM 7u5, JDK 7u5, JavaFX SDK 2.1.1 JavaFX 2.1.1 (Java EE JDK + Glassfish) I would be grateful if someone could tell me if there is something missing. I reinstalled almost all software java several times, but without success.

    Kind regards!

    Published by: 942925 on June 26, 2012 10:23

    Hello

    This message appears usually when the JVM cannot allocate sufficient memory. It may be the consequence of the stage Builder set - Xmx1024m command line: this is currently followed by default TLD-4515 and will be fixed in the next few weeks.
    For the time being you can give a try on a system with more memory. Moreover, what is your current hardware configuration?
    Concerning

  • PDF files are not in the list of applications preferences, pdf does not load

    I use Cougar and have Adobe reader installed 10.1.4. When I click on a site to download a pdf file, I get a white screen and no download (well before mountain lion) I went to the screen preferences/applications and pdf is not listed in the list of the app. How can I seem to me there so that I can assign an action to use the reader to open it.

    With earlier versions of Mac OS, some users have reported that they should disable the Acrobat plugin in Firefox and fall back on the Mac's default PDF reader when this happens. To try this, use

    Tools > Modules > Plugins category

    It works on the Mountain Lion?

    Regarding preferences, it is difficult to manually change the settings (mimeTypes.rdf) file, so hopefully it won't be necessary.

  • bad sound quality in the desktop version but not in the modern windows application

    I have a brand new Microsft Surface Pro 3 with all the updates that are installed and the latest version of Skype.

    When I use the modern windows application, the sound quality is very good.

    When I use the desktop app, it looks like wind. The poor sound is experienced by myself and the recipient and also when I echo test call.

    I uninstalled the windows application modern to have installed both causes a conflict.

    I tried to uninstall and reinstall the app without result.

    It is not the mouse or the speaker settings on my surface, because it works perfectly well when you use the modern windows application.

    any suggestions?

    I have now solved the problem by removing the MCO.

    For all those affected by the poor audio quality in Skype desktop client, please go to:

    Tools > Options > Audio Settings, then uncheck "Automatically adjust microphone settings" and "automatically adjusts the speaker settings.

    Credit for this fix is due to Tim Rolston of lovemysurface.net and I recommend his site to any other users of microsoft surface.

  • Do not open the following migration applications.  Adobe Application Manager missing or damaged

    Anyone know why I get the following message after I bought the new iMac and all migrated to the new machine via the time machine backup?

    None of my apps open cc. they all trow this error.  Redownloading and installing CC desktop does not help.

    "Adobe Application Manager, to solve this problem, is missing or damaged.

    Please download a new copy of Adobe Application Manager of

    http://www.Adobe.com/go/ApplicationManager ."

    Mac migration (or Time Machine) do not work with the Cloud program activations due to hidden files

    Sign out of your account... Uninstall... to run vacuuming...

    -Restart your computer... Sing into your account... Reinstall

    -using the vacuuming after uninstalling and before you reinstall may help

    -http://helpx.adobe.com/creative-cloud/help/install-apps.html (and uninstall)

    -http://helpx.adobe.com/creative-suite/kb/cs5-cleaner-tool-installation-problems.html

  • can not see the default host application

    I do not see the "host application" in the context menu under "open with".  It does not appear when you choose files on drive C, or when choosing files in a shared folder. I enabled sharing and checked the box to enable VMware open applications on the Mac.    I tried to uninstall and then install VMware tools several times.

    VMware 2.0.4

    MacPro 2x3ghz dual-core Xeon

    Mac OS 10.5.7

    In Windows XP if you right click on a file that resides in a shared folder of VMware and select the open with menu and don't see 'The Application host by default', it is normal if you have never opened such a file before to this virtual machine and you would need select open with > choose program... > default from the host Application and it will open the file in the default application on the host for that type of file and from that point forward for this file type then "default host Application" should then show directly in the open with menu.

  • «"" «... Illegal state exception»»» " Help!

    Here's my situation.

    I have an A screen that has a button and an ObjectListField and a button. Initially, the object list field contains a list of strings.

    What is push the button a new popup window appears, it contains a text field and a button. I use the display of the text field to get the input of the chain of the user and when the user presses the button, the precious screen containing the ObjectListField appears with the updated value.

    Here is my code

    -----------------------------------------------------------------------------------------------

    you manage the ESC but will also run great, it means that the screen is closed twice.

    put in a return after that manipulation of the ESC key should solve the problem.

  • Illegal state exception reading MCC

    Hello

    I use the method above to read MCC

    This is a good model for the treatment of the "start-up" which should mean that you can get your information from the Radio, once the device has started successfully.

    http://supportforums.BlackBerry.com/T5/Java-development/write-safe-initialization-code/Ta-p/444795

  • My site works in the United States but not in the Canada (I know sounds crazy)

    I have a client in the Canada who is having a few problems of very annoying site. The problem is when I test the site here in the United States, it works fine. I clear my caches and test the site on Chrome/Safari/Firefox and it works fine. I have my client the same thing, but they still run questions.

    They say the site:

    (1) takes more than 20 seconds to load, it takes only 8 seconds here in the United States.

    (2) they tell me that when they try and share a link on directly linked from the blog, they get a 404 error.

    (3) they say that the site does not work on the iPhone 5.

    Yet once, all these things have been tested here in the USA and I'm not able to replicate questions. What in the world could possibly happen?

    Here is the link to the site Kneed | Home

    Thank you

    Morgana

    Well, you use widgets 'localized' like the one for the card that, depending on the regions and the Internet, location of the provider may give different reslts, possibly including break completely, then the carrier of the supplier registration point to a different location than the one you are actually. The rest could be simply regional caching problems with TypeKit and your images and videos, but even on my fast fiber your page access charge with delay due to a large images used. The 404 would probably also fall into this category - you are being invited to a different resource at the regional level rather than one you do reference on the page. Loading times are also confirmed by your own comments - another 8 seconds is something that I would find much too long on what should be a simple thing. You need to spend time optimizing everything and check when cross-border is the features that you use, somehow...

    Mylenium

  • Active States works NOT in the latest version of adobe muse

    I thought that this problem has been fixed with the update?

    anchor links still do not work for me, I tried to re-insalling muse and still have the same problem.

    I checked that I have the latest version for windows 7.

    PLEASE FIX THIS!

    Thank you

    Many the majority of things in the Muse may have a hyperlink applied.

    Any block of text or a rectangle can be actually a button by using a hyperlink and by setting the attribute for the States of the text or graphics.

    The only time wherever there's a widget button States is when you want a mixture of text blocks or have other items to all States which are simultaneously triggered by a simple rectangular box, limit of the container of the button state.

Maybe you are looking for