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.
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 am working with Dialog based application.
My Question is that, I want to show Waiting dialog, until some database operation carried out.
i Used Derived class from CWinThread, but problem is that, when this thread close, the background (Main application dialog) remains at deactivated means( it hide behind another window).
i am thinking that, this is happening because of WaitDialog used CWinThread class.
The problem is not unique to a dialog based application. Creating windows of any kind in more than one thread is difficult and not recommended. In your case it sounds like your wait dialog is modal, while its parent dialog is in another thread. That is even worse and can lead to deadlocks between threads.
The reliable solution is to put the wait dialog (and all other GUI) in the main thread, and the lengthy database processing in a secondary thread.
Another alternative would be to use a Modeless Dialogbox which can also optionally show the status and call the DestroyWindow function when the database operation is completed -- you may need to disable some operations of the main window while the Modeless Dialogbox is visible, though.
From the comments on my previous answer, it looks like that alternative is not viable in this situation.
Maybe a better way would be to create a normal modal "wait" dialog box, start the background thread in the dialog's InitDialog, periodically check the status of the thread using a timer and end the dialog when the thread completes?
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 have written a .NET program, using Windows form Application.
My application is fairly simple.
Basically, I have two simple buttons on my form.
When the form is first loaded, I set up a global variable (bool run = true).
And my first button is essentially a very simple while loop.
while(run)
{
// do some code
}
And what I want to do, is have the second button set the value of the boolean to false (bool run = false).
But, once I clicked the first button, I cannot even touch the second button!
I have read quite about this, and I think my solution is to use a multi-threading.
I have found some example codes on line for multi-threading, and I tried to incorporate those, but I don't know why I cannot get it to work. Once I click button #1, there is no way for me to be able to click button #2.
Your UI thread should not have any infinite or a wait-on-something - never! You must not block the UI for anything (other than simple calculations, validations, user confirmation etc). You should make a thread for performing length task, and let that thread communicate to UI thread using asynchronous (or synchronous, if you prefer) communication.
On native Windows GUI application, you can use PostMessage (async), or SendMessage (sync). For .NET GUI applications, you can use Control.BeginInvoke (async), or Control.Invoke (sync).
Please read this article on how this is done.
I have written an application in LWUIT targeted for a J2ME phone (Sprint DuraXT). The application is for pickup and delivery van drivers. It receives dispatches from a back-end dispatching system that describe pickups and delivers the driver must make. As the drivers, execute the pickups and deliveries, the driver enters status information that is sent back to the dispatching system.
Now, during the processing of a pickup or delivery, the driver may be presented with error dialogs (incorrect field entry), yes/no confirmation dialogs (confirming some action) and information dialogs (indicating some status the driver should be aware of).
In addition, there is a background thread listening for dispatches coming from the back-end server. In the current implementation, this background thread can also create yes/no confirmation dialogs and information dialogs. These dialogs are more like an alert as they have an associated sound, but they are simply dialogs.
As long as these two dialogs do not occur “simultaneously” every thing works as expected. You can dismiss the dialogs and the app proceeds as expected.
However, when you are on a screen and there is a dialog already showing and a second one from the background thread occurs, you sometime wind up with the wrong screen showing and it is “frozen”. E.g. the soft keys have no effect.
My hypothesis is that there is a race condition between the threads that are dismissing the dialogs. It goes like this. The EDT is blocked showing the dialog that arises as part of the form’s logic. The background thread is also blocked showing a dialog. Now when the dialog showing on the EDT is dismissed, the form is restored, but the EDT may go off and display another form (via show()). When the dialog displayed by the background thread is dismissed, the form which was showing when the dialog was initially displayed is sometimes restored. Now, the display shows a different form than the one the EDT might have shown.
It is pretty clear that this problem is caused by the dialogs resulting from the activities of the background thread. So the basic question is: “How to handle the dialogs arising from the background thread?” I have some thoughts but none yield a particularly clean implementation. I am hoping somebody has had to deal with this same problem and has a suggestion.
I have tried synchronizing the dialog construction and display so that only one dialog can get displayed at a time. This certainly improves the UI, but does not fully resolve the problem. The race begins when the first dialog is dismissed. Here are some other ideas,
If a dialog is shown by a thread other than the EDT, call show on the form at the top of the display stack when the dialog is dismissed. This is a bit of a hack, but may be a workaround.
Run dialogs to be shown by the background thread on the EDT. There are several ways to do this, but the question is will it resolve the problem? Will using an EventDispatcher help? I have experimented using an EventDispatcher to fire an ActionEvent containing a subclass of a Dialog as a source. The subclass contains a show() method which invokes the correct form of the Dialog show method. The class holding the EventDispatcher (global to the application) listens for these events. When the event arrives, the show method is invoked. For information dialogs that simply continue execution from wherever they are dismissed, this should work. For yes/no dialogs, you may have to create something like yes/no callbacks to handle the bifurcation in the logic. And what is not obvious is if this will actually serialize the processing of the dialogs on the EDT thread. This seems complicated.
Any ideas?
I actually hit upon the solution after a bit of experimentation. Because the Dialogs are part of a more compilcated action involving yes/no Dialogs and database queries, I found I had to wrap the whole action in a class which implements the Runnable interface. Then I run the action via Display.getInstance().callSeriallyAndWait(runnable).
So others may benefit from this discussion, here is a example of one of these classes with the action embedded in the run method.
private class CancelOrder implements Runnable {
private KWMap order;
public CancelOrder(KWMap order) {
this.order = order;
}
public void run() {
String orderNum = getString(order, OrderTable.ORDER_NUM);
if (legStatusTable.isOrderStarted(orderNum)
&& !orderTable.isOrderComplete(order)) {
String msg = "You received a cancellation message for Order "
+ orderNum
+ " which has been started but is not finished."
+ "\nDo you want to keep it?";
if (app.yesNoDialog(msg, "Yes", "no")) {
sendCancelResponse(order, "Yes", "");
} else {
deleteOrder(orderNum);
sendCancelResponse(order, "No", "");
}
} else {
// order has neither been started nor completed.
deleteOrder(orderNum);
sendCancelResponse(order, "Yes", "");
app.alertDialog("Dispatcher cancelled Order " + orderNum);
}
}
}
The key thing here is that the action contains logic depending on how a user responds to a yes/no Dialog and there are operations on an underlying database and messaging subsystem as well. Except for the Dialogs, nothing in this action blocks the EDT for more than a few 100s of milliseconds, so the application runs very smoothly. The app coorectly handles dislogs stacking on top of each other which was a problem with the simple apporach of letting these actions run on the background (non EDT) thread.