i have an JavaFX based input view. From this view a build up another view with JUNG/jungerer (a graph framework).
No i want to realize, that a ChoiceDialog appears, when a user clicks on a vertex in this graph.
I know how to build up the ChoiceDialog and how to get the result of the choice.
The only problem is, when i click on a vertex in the graph and call the function to build up the ChoiceDialog following Exception is throwed:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = AWT-EventQueue-0
I tried it with
(javafx.application.Platform/runLater f)
f is a function that is called with "runLater".
Does anybody know a solution for this very stupid problem?
I think the problem is, that the graph ui is in a own JFrame..i tried to initialize the jframe in the thread where the input view is running..but that didn't work to..
Thanks!
Related
I have a simple question.
In my UWP app I am using multiple threads and while on a background thread when i try to create a simple BitmapImage by using code: var image=new BitmapImage();. It throws an exception
The application called an interface that was marshalled for a different thread.
this exception occurs on the very line where I try to create the image. I simply want to create this image, deal with its properties and then store it in my datalist.
Note: datalist is a simple public static property which is accesible throughout the app. thankyou
I can't see the full context from the question, so I am not sure why this exception is bubbling up, but one sure way to fix it is using CoreDispatcher.RunAsync().
The documentation says:
If you are on a worker thread and want to schedule work on the UI thread, use CoreDispatcher::RunAsync.
If you are using MVVMLight, you can also make use of it's DispatcherHelper class' CheckBeginInvokeOnUI method. It's a bit better, since it first checks which thread it is called on and if it's the UI thread, it executes the action immediately and passes it to the UI thread only if needed.
I have a requirement to generate a bitmap out of an EditText and then perform some manipulations on it.
My main concern is not to call View.buildDrawingCache() method on the UI thread and possibly block it, especially when talking about large screens (i.e. Nexus 10) since the EditText will occupy about 80% of the available screen size.
I execute Runnables inside a ThreadPoolExecutor, those will inflate dummy views on a worker thread and set all the required attributes to them, then simply call buildDrawingCache() & getDrawingCache() to generate a bitmap.
This works perfect on some devices yet recently I have encountered a few devices that crash with the following message:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I understand why this happens, as some phones must have modified implementation for EditText that creates a Handler and thus requires Looper.prepare() to be called first.
From what I've read online there is no issue with calling Looper.prepare() inside a worker thread though some stated it is highly unrecommended yet I could not find a reason for that.
Other than that, most posts related to this issue state you are not supposed to inflate views inside a background thread, probably due to the following from Android's official documentation (Processes and Threads):
"Do not access the Android UI toolkit from outside the UI thread"
What is the recommended approach to dealing with this problem?
Is there any harm in calling build/get drawingcache from the main thread? (performance-wise)
Will calling Looper.prepare() inside my worker thread solve this problem?
EDIT
Just to elaborate on my specific requirement, I have a user-interface consisting of an ImageView and a custom EditText on top of it, the EditText can change it's font and color according to the user selection, it can be zoomed in/out using "pinch to zoom" gesture and can also be dragged around to allow the user to reposition it on top of the image.
Eventually what I do is create a dummy view inside my worker thread using the exact same values (width, height, position) it currently has on the UI and then generate it's drawingcache, the original image's bitmap is decoded again from a local file.
Once the two bitmaps are ready I merge them into a single bitmap for future use.
So to put it simple, is there anything wrong with executing the following code (from within a background thread):
Call Looper.prepare()
Create a new view with application context, call measure() & layout() manually and then build+get drawingcache from it, i.e.:
Looper.prepare();
EditText view = new EditText(appContext);
view.setText("some text");
view.setLayoutParams(layoutParams);
view.measure(
View.MeasureSpec.makeMeasureSpec(targetWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(targetHeight, View.MeasureSpec.EXACTLY));
view.layout(0, 0, targetWidth, targetHeight);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
How does this apply to the restriction with not accessing the Android UI toolkit from outside the UI thread, what could possibly go wrong?
In your case, you can do it of course, but be carefull only reading values from UI data, to avoid synchronizations bug.
Also you should not recreate the EditText from the background thread, it will be more efficient to directly access the already existant one instead:
Looper.prepare();
myEditText.setDrawingCacheEnabled(true);
Bitmap bitmap = myEditText.getDrawingCache();
If your question is : why it is not recommanded by android guidelines, here is a good SO answer to your question.
Calling View.buildDrawingCache() calls Bitmap.nativeCreate which can be a large allocation, so yes, it can be potentially harmful to run on main thread. I don't see a problem with calling Looper.prepare() in your background thread. However, it's unclear what you are trying to achieve and there may be a better solution to your problem.
The reason you are not supposed to the UI toolkit from other threads is that it is not written to be thread safe it is written under the assumption that only one thread runs it. This means it's really hard to tell what can go wrong, the bad effects, if any, will mostly happen in an un-repeatable due to specific timing of threads.
Your description of what you are trying to do it not too clear. In your case, I would just allocate a large bitmap, and draw text into it. Why are you using the EditText in the first place ? It seems like a kind of a hack, and hacks tend to break eventually.
Why View.buildDrawingCache()? What about using View.draw(Canvas canvas) to manually render to a Canvas backed by a Bitmap? Method seems simple enough to not cause problems on background threads.
EditText edit = (EditText)findViewById(R.id.edit);
edit.buildDrawingCache();
ImageView img = (ImageView)findViewById(R.id.test);
img.setImageBitmap(edit.getDrawingCache());
Lalit when you try to build the cache in the onCreate method, the drawing hasn't happened yet so the drawingCache should have nothing. Either put the buildDrawingChache method in the onClick method. Or use the following code in onCreate.
ViewTreeObserver vto = editText.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
editText.buildDrawingCache();
}
});
I also encountered this error a few times already:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
my solution:
new Thread(new Runnable(){
#Override
public void run(){
//add implementations that DOES NOT AFFECT the UI here
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run(){
//manage your edittext and Other UIs here
}
});
}
}).start();
just create a handler inside your worker thread to apply data changes to your UI
I'd like to have a class respond to the morphic "step" message - but the class doesn't need to be displayed (directly)... so it's not a Morph
is there a way to use this message outside of morphic, or is there a morph without a displayed UI?
with thanks
Chris
World doOneCycle may help.
The UI process repeatedly calls World doOneCycle. You can do that too. Just ensure your do that in the main thread.
I'm using swing to display multiple javafx Tableview, each embeded (thanks to JFXPanel) in a swing TabbedPane
I use the well know pattern described in the oracle doc, in scala way :
implicit def fun2Run[T](x: ⇒ T) = new Runnable {
def run = x
}
def myTabbedScene():Scene = {
val root = new StackPane
root.getChildren.add(new Label("Hello world!"))
new Scene(root, 300, 300)
}
def initFxPanel(fxPanel: JFXPanel, s: ⇒ Scene) = {
fxPanel.setScene(s)
}
def initSwingGui(panel: PluginPanel) = {
val fxPanel = new JFXPanel()
// code to add panel to JPanel
panel.peer.add(fxPanel)
Platform runLater initFxPanel(fxPanel,myTabbedScene())
}
val jfxSwingPanel = new PluginPanel("wrap 2") {
var jtemp = new JPanel()
contents += jtemp
}
SwingUtilities invokeLater initSwingGui(jfxSwingPanel)
This code is executed each time the user open a new swing tab (only scene method differs) but i'm not sure this is the best way to manage thread in this case :-/
When i close or open a tab, i have some incoherent state in my application and error during display.
An example of my use case, and somes questions linked :
I open a first tab J1, a runlater is invoked, my scene display without problem in the tab.
I open a second tab J2, a new runlater is invoked on javafx Thread,
I switch to tab J1, how display in my tab is refresh ? An implicit runnable action is launched to main thread to make this possible ? How javafx recognized the good tab to refresh ? If i have a button which launch some action, i launch a runlater() action on the javafx main thread which dispatch ?
Update:
I find a code source which can help reader on this point, you can revalidate() or/and repaint() your swing panel (here _contentpane) which contain your jfxPanel
SwingUtilities.invokeLater(new Runnable() {
public void run() {
_contentPane.add(_jfxPanel);
_contentPane.revalidate();
_contentPane.repaint(); }});
I close the first tab J1, javafx automaticly close/garbage the javafx resource associated?
I have multiples other general questions :
How javafx application main thread manage this multiple runlater() call
when they arrive from different jfxpanel in swing ?
How can i close properly the resources (without close main javafx thread with exit() Platform method) associated to my jfxpanel when user close a tab ? If i destroy the JFXPanel,javafx resources used to display are liberated ?
Using task to manage my thread can be an answer to my problem ?
My question are probably naive, but i start in gui building, and i have problem to understand how javafx manage scene on different embedded panel.
How javafx application thread manage this multiple runlater() call when they arrive from different jfxpanel in swing ?
From the Platform.runLater 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.
Further:
How can i close properly the thread (without close main javafx thread) which execute my jfxpanel when user close a tab?
It's unclear which thread you are referring to. In general, when integrating JavaFX and Swing there are only two threads to be concerned with - the Swing dispatch thread and the JavaFX application thread - both of which should be managed by the respective underlying frameworks and you don't need to explicitly close. You don't need any other threads unless you are trying to do something which should not execute on either of those threads (such as a highly CPU intensive task or a remote I/O) - which from your sample code would not be appear to be the case.
Using task to manage my thread can be an answer to my problem ?
Unless you have a specific need for such a thing, such a solution would likely further complicate your situation than improve it.
I close the first tab J1, javafx automaticly close/garbage the javafx resource associated?
If you don't keep a reference to any of the resources in the related jfxpanel, then the Java Virtual Machine can garbage collect the jfxpanel and and resources associated with it - this is just standard Java garbage collection technology, nothing special here.
I switch to tab J1, how display in my tab is refresh ? An implicit runnable action is launched to main thread to make this possible ?
Sounds like a bad idea (the main thread in Java terms is the thread used to launch the Java's main function and is not involved in GUI programming at all). You probably want to submit your runnable refresh request via Platform.runLater() so that it will be executed on the JavaFX application thread.
How javafx recognized the good tab to refresh ?
You have a JavaFX JFXPanel in each swing tab and each swing tab knows which JFXPanel it has, so when you invoke Platform.runLater to refresh the specific panel, pass a (final) reference to the JFXPanel to be used. Here is some psuedo-code in no language whatsoever to illustrate the concept:
on swing tab change event
final JFXPanel curPanel = tab.getJFXPanel()
Platform.runLater() {
// update curPanel here...
}
If i have a button which launch some action, i launch a runlater() action on the javafx main thread which dispatch ?
In essence I think you are correct here, I'll just rewrite your question to clarify some of the terminology - let's say it's a swing button and on performing an action on the swing button, you make a call to Platform.runLater, then the code in the runLater call will be eventually be executed on the JavaFX application thread.
Other questions I cannot answer as I am not fluent enough in Scala to provide a reasonable answer.
Honestly, if you are just starting GUI building, then my unsolicited advice would be to use Java rather than Scala and stick with either Swing or JavaFX, but not mix it all together until you are really comfortable with the GUI building process - otherwise there are just way too many traps and pitfalls you may encounter during the integration that few will be able to assist you with.
I have a ultragrid which is bound to a datatable, i update datatable in a thread (not a gui thread). My question is that while updating datatable do I need to delegate it on gui thread (so that update on grid happens in gui thread) or I can simply update datatable in any thread and infragistics grid takes care of updating itself in correct thread?
I couldn't find answer to simple question in infragistics online help or docs.
thanks
You need to update the data source on the UI thread. There are some similar discussions on the Infragistics forums, for example: one, two, three.
best way i found to do this was to use a synchronizationContext object to post the .add call to the GUI thread.
in my situation i have classes with a property of type synchronizationContext that i set to SynchronizationContext.Current when the class is initialized. then i can call something like:
SyncContext.Post(Sub()
_displaySource.Rows.Add(r)
End Sub, Nothing)
when the class is running on a different thread and it works fine. without this you will get the annoying red X occasionally