not on fx application thread как исправить
Как избежать Не использовать поток приложений FX; currentThread = ошибка приложения JavaFX Application Thread?
ОТВЕТЫ
Ответ 1
Platform.setImplicitExit(false); решил мою проблему. Я думаю, что они изменили реализацию в JavaFX 8, поэтому тот же код, который работает без каких-либо проблем в JavaFX 2, дает не ошибку потока приложений fx.
Ответ 2
также исправит это.
Ответ 3
Это произошло со мной, когда я изменял элемент пользовательского интерфейса из задачи в javafx 2, например элементы списка. Задача, которая изменяет график сцены, помогла мне решить проблему, т.е. обновление элементов пользовательского интерфейса с помощью
Ответ 4
Это должно произойти при попытке изменить некоторый пользовательский интерфейс компонента, как текст ярлыка. Так работает всегда:
Ответ 5
Вы можете изменить форму или перейти к другому представлению или fxml с этим в любой части вашего кода:
Мой пример в моем контроллере:
Ответ 6
Он явно не показан в приведенном выше коде, но я уверен, что происходит то, что где-то вы создаете поток вне основного потока javafx приложения, а затем пытаетесь выполнить операции над javafx-объектами (например, закрытие, открытие окон и т.д.) в SECOND thread. Это строго запрещено, так как только основной поток может напрямую управлять объектами javafx. Если это становится требованием вашей программы, вам нужно использовать второй поток для других вещей, таких как вычисления, и т.д. И т.д. Вы должны использовать некоторую форму передачи сообщений, чтобы другой поток знал, что вы хотите делать все действия javafx.
Ответ 7
я меняю версию jdk (1.8.0_31 на 1.8.0)
Ответ 8
Я столкнулся с той же проблемой при попытке добавить заставку для моей программы. Вот как мой код был
Запуск этого приложения дал «не в приложении fx». Добавив Platform.runLater() внутри моей задачи, это решило проблему. Вот как у меня сейчас есть код:
Я надеюсь, что это поможет вам решить проблему. Приветствия.
How to avoid Not on FX application thread; currentThread = JavaFX Application Thread error?
7 Answers 7
This happened with me when i was modifying UI element from task in javafx 2 like listview elements.A Task Which Modifies The Scene Graph helped me to solve the issue i.e. updating UI elements by
It should happens when you try to change some component UI, like a label text. Running like that works always:
Platform.setImplicitExit(false); solved my problem. I think they changed the implementation in JavaFX 8, so the same code that works without any issue in JavaFX 2 gives the not an fx application thread error there.
You can change of Form or go to another view or fxml with this in any part of your code :
My Example in my Controller :
It’s not shown explicitly in the code above, but what I’m fairly sure is happening is that somewhere you are creating a thread outside of the application (main) javafx thread, and then you are trying to preform operations on javafx objects (like closing, opening windows, etc.) on the SECOND thread. This is strictly not allowed, as only the main thread can control javafx objects directly. If this becomes a requirement of your program that you need to use the second thread for other things like computations, etc, etc. You must use some form of message passing to let the other thread know that you want to do whatever javafx action.
I experienced the same problem while trying to add a splash screen for my program. This is how my code was
Running this gave a ‘not on fx application’. By adding Platform.runLater() inside my task, that solved the issue. Now, this is how I currently have my code:
I hope this will help you solve the problem. Cheers.
Not on FX application thread; currentThread = Thread-5 [duplicate]
I’m making a text editor and I want to add a status-bar in the footer that tells user different tips after a few seconds and I’m facing this error when I try to set text on the label but when I try to set that text on console that works fine.
1 Answer 1
The only thread that is allowed to modify the JavaFX GUI is the JavaFX thread. If any other thread modifies the UI, you will get an exception.
Platform.runLater() has the following javadoc:
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater. If this method is called after the JavaFX runtime has been shutdown, the call will be ignored: the Runnable will not be executed and no exception will be thrown.
NOTE: applications should avoid flooding JavaFX with too many pending Runnables. Otherwise, the application may become unresponsive. Applications are encouraged to batch up multiple operations into fewer runLater calls. Additionally, long-running operations should be done on a background thread where possible, freeing up the JavaFX Application Thread for GUI operations.
This method must not be called before the FX runtime has been initialized. For standard JavaFX applications that extend Application, and use either the Java launcher or one of the launch methods in the Application class to launch the application, the FX runtime is initialized by the launcher before the Application class is loaded. For Swing applications that use JFXPanel to display FX content, the FX runtime is initialized when the first JFXPanel instance is constructed. For SWT application that use FXCanvas to display FX content, the FX runtime is initialized when the first FXCanvas instance is constructed.
I don’t think your code is structured in the best way to accomplish this task, but a very simple solution is the following:
A better solution to your problem may be to use an AnimationTimer.
Here is a useful thread on how to accomplish that: JavaFX periodic background task
Как избежать ошибки Not on FX application thread; currentThread = JavaFX Application Thread?
7 ответов
Приложение реагирует на действия, которые происходят на геймпаде. Когда кнопка нажата, что-то происходит на UI. Но я столкнулся с проблемой с зависанием приложения или исключением java.lang.IllegalStateException: Not on FX application thread. Чтобы исправить это, я попробовал следующие подходы.
У меня возникла проблема при переносе приложения с Swing на JavaFX. Чтобы сделать это как можно проще, в начале моего приложения JavaFX Stage инициализируется в основном классе JavaFX (Main.java). В конце инициализации (в потоке JFX) я открываю Swing customed JDialog (на данный момент не.
Это должно произойти, когда вы пытаетесь изменить какой-либо компонент UI, например текст метки. Работать так, как это работает всегда:
Вы можете изменить форму или перейти к другому представлению или fxml с этим в любой части вашего кода :
Мой пример в моем контроллере :
У меня есть приложение javafx 8, которое имеет несколько активных потоков, когда я хочу закрыть его, этот код показывает 8 активных потоков : ThreadGroup group = Thread.currentThread().getThreadGroup(); LOG.debug(Number of active threads = + group.activeCount()); Использование Platform.exit(); и.
Я делаю игру на основе step-by-step с JavaFX и использую do while loop, чтобы дождаться ввода пользователя. Проблема в том, что он вызывается из метода инициализации контроллера fxml, и это означает, что интерфейс никогда не будет загружаться. Решение состоит в том, чтобы ждать, используя другой.
Это явно не показано в приведенном выше коде, но я совершенно уверен, что где-то вы создаете поток вне потока javafx приложения (основного), а затем пытаетесь выполнить операции над объектами javafx (например, закрытие, открытие windows и т. Д.) В потоке SECOND. Это строго запрещено, так как только основной поток может напрямую управлять объектами javafx. Если это становится требованием вашей программы, вам нужно использовать второй поток для других вещей, таких как вычисления и т. Д. И т. Д. Вы должны использовать какую-то форму передачи сообщений, чтобы другой поток знал, что вы хотите выполнить любое действие javafx.
Я столкнулся с той же проблемой, пытаясь добавить заставку для своей программы. Вот каким был мой код
Запуск этого дал «не на fx приложение». Добавив Platform.runLater() внутри моей задачи, это решило проблему. Теперь вот как у меня сейчас есть мой код:
Я надеюсь, что это поможет вам решить проблему. Овации.
Похожие вопросы:
Я создаю приложение Netty/JavaFX и столкнулся со следующим исключением, когда пытаюсь отправить картинку с клиента на сервер. Exception in thread nioEventLoopGroup-3-1.
Я хотел бы создать всплывающее окно в scala с javafx final val popup = new Popup val text: Text = new Text(s) popup.setAutoFix(false) popup.setHideOnEscape(true) popup.getContent().addAll(text).
Приложение реагирует на действия, которые происходят на геймпаде. Когда кнопка нажата, что-то происходит на UI. Но я столкнулся с проблемой с зависанием приложения или исключением.
У меня возникла проблема при переносе приложения с Swing на JavaFX. Чтобы сделать это как можно проще, в начале моего приложения JavaFX Stage инициализируется в основном классе JavaFX (Main.java). В.
У меня есть приложение javafx 8, которое имеет несколько активных потоков, когда я хочу закрыть его, этот код показывает 8 активных потоков : ThreadGroup group =.
Я делаю игру на основе step-by-step с JavaFX и использую do while loop, чтобы дождаться ввода пользователя. Проблема в том, что он вызывается из метода инициализации контроллера fxml, и это.
Все знают, что только JavaFX поток должен быть разрешен для изменения GUI в JavaFX приложениях, но я получаю странное поведение вокруг нарушений этого правила много раз, поэтому я написал эту.
JavaFX works fine on jdk7 but not on jdk8: Not on FX application thread
I recently encountered this problem:
java.util.NoSuchElementException Exception in thread «Thread-4» java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
The code works on jdk7 but not on jdk8, the code look like this:
Then i call this thread from this code:
All I want to do is change the values/properties of the controls from other threads which have functions just like in my example it scans for the next string then append it to the TextArea.
Why it works on jdk7 but not on jdk8? pls. explain.
I’ve done some research and the solution i came up to this JavaFX task and service but, i dont get them and there are no good examples online.
2 Answers 2
Your code is actually broken on JDK7 too. It is illegal to change the state of UI controls from a background thread (i.e. not from the FX Application Thread). Like almost all UI toolkits, JavaFX uses a single threaded model, and provides no synchronization on UI elements. Consequently if you change or view the state of a UI control from a thread other than the FX Application Thread, your code is prone to unspecified and unpredictable behavior.
The fix is to update your UI controls on the FX Application Thread:
If you are now using Java 8 exclusively, you can replace the anonymous inner class with a lambda expression:
(and there’s no longer any need to declare ta as final, though there are still restrictions).