I've been trying to figure out how to go from a JFrame to my java class.
This was my code so far: (It only opens the main..which is the JFrame)
Process process = Runtime.getRuntime().exec("cmd.exe /c start java -jar \C:\Users\Admin\Documents\NetBeansProjects\Program\dist\Program.jar");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
The main used to be the class, making it easy for me to use setvislble() for the frame, but now I need it backwards and the main is now the JFrame. I need to know how to open the class file. (Also if anyone knows how to switch besides using CMD that would be great!)
I've tried used this plus a combination of other variations but it won't work.
java -cp "C:\Users\Admin\Documents\NetBeansProjects\Program\dist\Program.jar class"
JFrame button, if my understanding is correct, does not handle infinite loops well.
The idea is not to block the EDT, but there are certainly correct ways to repeat an action (until told otherwise) in Swing, as well as ways to do long running tasks. Here is some advice I commonly give:
Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. See Concurrency in Swing for details and the fix.
But back to the matter at hand..
..getting the user to input information in the GUI, then sending that information into a text file. The class reads the text file, gets the information and does its things..
OK that is 10 different kinds of wrong.
Let's say the GUI is called GUI.class, the other class is called Worker.class.
Worker.class
This class might have a no-args constructor as well as a constructor that accepts an InputStream (for the text file, if it is finally needed).
The Worker class might have a main(String[]) that creates an instance of a Worker object. It might use either:
An InputStream for the constructor of the Worker, from which it would configure the fields needed for the work to be done.
A no-args constructor for the Worker instance, then use setter methods for configuring it. (Maybe prompting the user through the command line to supply the information.)
Once the main has done that, call execute() on the Worker instance and call getter methods for the results, then write the results to System.out.
GUI.class
The GUI can also use a Worker instance. It would probably use the no-args variant then bind the setter methods to the input controls in the GUI. Once the user clicks the Execute button, execute() the process, then query the getter methods to display the results to the user (still in the GUI).
Related
I start several(threads) instances of a java class that receives an "input" and based on that generates an "output" on out it out on the standard output(screen). I would like to add an option that would enable me to send this output to a single JFrame (text area). What is the best way of doing this? Up to this point my program was totally GUIless but I would like to make it a bit more GUI friendly and add this option.
The challenge is that at any given point I could have several threads running. Any design or code snippets would be greatly appreciated.
As MadProgrammer points out, a nice, encapsulated way of doing this is SwingWorker.
That said, here is the general theory:
All updates to Swing components must be done on the Swing event dispatch thread (there are some exceptions, but not relevant here). This is achieved by SwingUtilities.invokeLater() (and occasionally invokeAndWait() ).
The Swing runtime will then queue up the changes you want to make and call them one at a time. This makes the entire problem of updating your text area pretty trivial: just create a Runnable with the text you want to append, pass that to invokeLater(), and have your Runnable grab the document model of the text area and append your desired text to it.
SwingWorker can encapsulate some of the complexities of background thread management, but I encourage you to do it the 'hard way' a time or two (and your use-case is actually easier to do the 'hard way'). That way you can appreciate what SwingWorker does for you when you do need it.
You need not to convert your existing threads to SwingWorkers. Just let them from time to time send messages to JFrame in a way like this:
EventQueue.invokeLater(new Runnable(){
// update GUI
});
To avoid boilerplate code, it is good to wrap programming interface to the screen with a java.lang.reflect.Proxy. An example of such wrapping is at SwingProxyActorTest.java.
Situation: a main form calls a modal jDialog with textboxes in which parameters are filled in by the user to create or modify an instance of a certain class, call it ClassA.
When the dialog needs to modify an existing instance, it is passed in the constructor as a parameter. Otherwise the jDialog will create a new instance of ClassA.
Problem: the mainform needs to access that new instance, and I think it is unclean code to pass the entire main form as a parameter, and let the dialog push the new instance into it by a method call, because that way a perfectly re-usable stand-alone dialog becomes only usable with one single main form that needs a certain classname and method to receive the new instance.
It is much more logical to make the main form get the new instance from the jdialog after the OK button is clicked, by calling a getClassAInstance() method (which could be called also when an existing instance was being modified). The method is called after the "setVisible(true)" method on a new instance of the jdialog in question. The dialog appears, the thread of the main form will sleep until the dialog is closed (because it is modal). The OK button calls the dispose() method of the jDialog, then the very next statement is the getClassAInstance() call on the jDialog by the mainform.
Here's the same thing in code..
ClassAInstanceMakerDialog imd = new ClassAInstanceMakerDialog(this, true);
imd.setVisible(true);
//imd.dispose(); after OK button click
System.out.println(imd.getClassAInstance()); //return a new ClassA instance
//output: whatever ClassA.toString() should return, works fine
Question: I've tried it and it seems to work perfectly fine. But, is it a good code? Is there any danger of the getClassAInstance() method returning "null", because the garbage collector collected the ClassA instance after the jDialog was disposed and before the main form could complete the call?
Please excuse me if I didn't make myself clear, I'm not a native English speaker. If you would rather see some code, let me know...
I think it's perfectly legal to access the member variable of your dialog instance that holds the ClassA instance, the dialog instance will not be garbage collected until it goes out of scope, not just because you called dispose on it.
I'd give slight preference to a solution where you define an event handler interface with a signature of
someThingHappened(ClassA toThisObject), make your mainform or anything that might be interested that ClassA thing implement that interface make it possible to add listeners to the dialog before making it visible.
That way, you would loosen the coupling between the dialog and the main form a little.
I don't think that dispose() sets the JDialog up for garbage collection, but instead just releases resources. The dialog is still re-usable as per the Window API (since JDialog inherits this method from Window):
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
As long as there are valid reachable references to the JDialog object still present, it will not be garbage collected. I think that the cost of disposing the dialog is that your code will need to spend a (very) little bit of time to re-create the resources.
It is perfectly reasonable and appropriate to have an IDisposable include properties or methods which may be used after Dispose is called to return information about things which happened before Dispose was called. Rather than blindly enforcing a rule that any and all methods of a disposed object should throw an ObjectDisposedException, one should instead consider which methods and properties do or do not make sense on disposed objects. Attempting to access a disposed object should throw ObjectDisposedException in preference to re-acquiring released resources or letting escape some other exception which occurs as a consequence of the disposal. If the method or property access can succeed without any of the released resources, it should often be allowed to do so.
I have been taught only to manage the GUI through the event dispatcher thread. Currently I am using a textArea.append("something"); outside of the event dispatcher thread, but I want this to always happen at the start of running the program. How can I set a listener to act upon the start up for the program or is what I have done acceptable?
Use the constructor JTextArea(String text) on creating it.
One solution is to create a method in the Class containing the JTextArea called localInitialization() or something like it, which is called in the class's constructor directly after initComponents(). This allows you to put your own custom start-up conditions especially if you are using a GUI Builder such as the one in NetBeans where you cannot edit initComponents().
i'm not a java developer, but i need to write a small applet to upload file via ftp
(actually, i'm a web developer). Everything works fine, except for the way that feedback messages are displayed. Let me explain with an example:
if i wrote sometingh like that, inside a method (controlled by a click event)
//....
myJpanel.setText("Connecting to remote server");
//actually, it's surrounded by try-catch statement
myFtpObject.connect(); //this is taken from a third part package
myJpanel.setText("Connected")
When I try to run this code the connection is set (after that connection I upload files with no problem), but inside the Jpanel myJpanel I immeditaly read "connected" (altought it takes several seconds to connect) and I never see the "Connecting to remote server" string.
It sounds to me like the Jpanel setText method is buffered in some way.
How can I display messages in real time?
(I've tried to do System.out.println for testing and it worked great!)
Thanks
if i wrote sometingh like that inside a method (controlled by a click event)
Code executed in an event listener executes on the EDT. The problem is that the long running task is blocking the Swing EDT. So the GUI never gets a chance to repaint itself.
Read the section from the Swing tutorial on Concurrency for more information and for a solution. The basic solution is to create a separate thread for the long running task.
This is also why System.out.println(..) works, because it executes on a different Thread.
I hoped someone might be able to help as I'm a little stumped. I have a javafx class which runs a user interface, which includes a button to read some text out loud. When you press it, it invokes a Java object which uses the FreeTTS java speech synth to read out loud a String, which all works fine.
The problem is, when the speech is being read out, the program stops completely until its completed. I'm not an expert on threaded applications, but I understand that usually if I extend the Thread class, and provided my implementation of the speech synth code inside an overridden run method, when I call start on the class it "should" create a new Thread, and run this code there, allowing the main thread which has the JavaFX GUI on to continue as normal.
Any idea why this isn't the case? Thanks a lot in advance!
Ack - I've solved it! I called the start() method of the class rather than run() and its sorted. Seems so obviously when looking now!