How do I call the same instance of a JFrame say A from 5 different JFrames if I need the display of A to be updated every time I call it??
One way is to provide a reference to the frame to each of the 'child processes' and a public method that will update the UI.
Or since it is better not to extend JFrame, a utility class that has a reference to the JFrame and provides the public method.
BTW: Most apps. would have only a single JFrame. The way to handle the situation you describe might be better implemented using JDialogs or JOptionPanes for the 'secondary' windows. Or to collect all the GUI elements together into the main frame: JDesktopPane/JInternalFrames, CardLayout, JTabbedPane..
Related
I have a class that creates a JFrame. When the JFrame is created it has a start button. When the start button is clicked, it runs two threads until the stop button is clicked. The two threads are in another class file. From the class that contains the threads, how can I access the JFrame instance in order to change value that are displayed?
In order to acheive this you have to pass the reference of JFrame using this keyword.
To have access to a private instance within another class, I think you should use agetter.
Example:
//JFrame declaration
private JFrame frame;
//Getter
public JFrame getFrame() {
return frame;
}
As noted by one answer, you can pass in a reference of the GUI or view into any class that needs it, for instance by passing the GUI class into the other class's constructor parameter, and using the parameter to set a field, but having said that, there are caveats:
Always be sure to make Swing state changes on the Swing event thread (the EDT). Since you're using background threading, this means that you will either
use a SwingWorker as your background thread, and notify the GUI of changes via the publish/process method pair, or
your SwingWorker can notify observers of change via PropertyChangeListeners and "bound" properties, or
if using a standard Thread/Runnable, you will need to be sure to queue Swing calls onto the EDT using SwingUtilities.invokeLater(someRunnable)
Even better is to use a Model-View-Control type structure, but even if you do this, the model should be changed on the EDT for the same reasons above.
As a side recommendation in general I try to avoid making classes that extend JFrame as that unnecessarily restricts my code to creating just JFrames.
Note that this help is very general, but if you need more specific help, then you will want to post more specific information regarding your problem and your pertinent code.
I want to fill values of multiple jTextBox from a jFrame into another, using accessor methods like
String getNameVal()
{
return jTextBox1.getText();
}
How to call these methods from another jFrame?
Suggestions:
It sounds like your GUI code is geared towards making JFrames, and if so, you will want to avoid this. You are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this.
More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
This question has direct bearing on your problem. I will guess that your main problem isn't how to give classes getter methods, and how to have other classes call the getter methods. More often then not, when faced with the issue of extracting information from one GUI view to another, the issue is one of when to extract the information. If you displayed your second window as a non-modal JFrame, and then had the calling class immediately extract the data from that second JFrame, you'd get nonsense data, because you'd be extracting data before the user would have time to interact with the 2nd window and enter data.
One possible solution to this when using non-modal windows to get information from the user is to use a WindowListener so you can be notified when the user has completed his dealing with the second window, and so now data can be safely extracted.
Often better is for the 2nd window not be non-modal, as JFrames are, but instead to be a modal window such as a modal JDialog. When the calling code displays a modal dialog, all code flow in the calling code stops until the dialog is no longer visible. In this situation, no WindowListener is needed since you will know exactly when the dialog has been dealt with -- on the code line immediately after you set it visible -- and so can extract your data from it with ease.
A nice variant on this has already been mentioned in by Andrew Thompson in comments -- use a JOptionPane. Don't poo-poo this option since JOptionPanes are powerful tools, likely much more powerful than you realize as they can hold fully formed complex JPanel views, and behave just as described above, as modal dialogs.
If you need more specific help, then please don't hesitate to comment to this answer. Also if so, then consider creating and posting a Minimal, Complete, and Verifiable Example Program where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.
Edit
For my mcve code examples of the above suggestions, please my answers to the following StackOverflow Questions:
Using a modal JDialog to extract information
Using a JOptonPane to extract information
I assume the textfields are present in frame1 and you want to access them in frame2. The following can be a way to achieve this:
First create getters for all JTextFields that you have in your frame1. Alternatively you can have them in a panel and call getComponents() method.
Create a private variable of JFrame type in your frame2.
Modify the constructor of frame2 to receive the frame1 object and assign it to the private variable of JFrame type.
Now you can create a close() method in frame2 which disposes the frame2 and sets frame1 to visible.
But in my opinion you should create a class which handles the data in these textfields. Initialize the class object in any button click of frame1 and check for any inconsistency in the input. I can guess there is something wrong with your design.
So for the sake of simplicity I set up a little test code just to figure out this problem. Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this.
f.remove(this);
thing t = new thing();
f.add(t);
f.setVisible(true);
f being my JFrame object and 'thing' is just another class extending JComponent that paints a blue background..
when I comment out setvisible() it no longer changes to blue.. I've tried using t.setVisible(true) but it seems I have to make the frame visible again, not the component
does anyone know why I have to call that... or if there is another way to change components within a single frame?
"Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this."
Don't "sleep" your program. Instead use a java.swing.Timer to perform repeated tasks on the GUI or for animation. See more at How to Use Swing Timers. You can see a bunch of Timer examples here and here and here and here and here
Instead of trying to add and remove panels look into using a CardLayout which allows you to switch between views. It will help you avoid a lot of problems that come with with adding and removing components/containers. See more at How to Use CardLayout. Also see a simple example here.
To answer your main question, whenever you remove and add components from your frame, you need to revalidate() it. setVisible() takes care of that for you.
Side Note
Seems like a lot adding an removing background panels) just to change the background. Why not just setBackround()? You can switch colors with the use of the Timer
Calling setVisible(true) makes the frame appear onscreen. Sometimes you might see the show method used instead. The two usages are equivalent, but we use setVisible(true) for consistency's sake.
In the GUI book we use in class there are many examples of how graphical user interfaces are made in Java. So many examples, that I'm very confused regarding which one should be used when it comes down to a big application.
So I've seen examples
in which the main class extends JFrame
where the JFrame object is created inside the main method
where the main class extends JFrame AND implements ActionEvent interface
where Listener classes are declared inside the main class
Sure, I can work with all of these, but right now, as I don't have any kind of experience, I don't see the benefit of using any of them. Is actually one of them the correct way to do it or it depends on my sittuation?
Thank you!
"Is A" or "Has A"? This is the question that should be asked when considering extending a class. If the new class "Is A" frame, extend frame, but if the class just needs a reference to a frame, don't extend.
In fact, if a custom component is required, extend a JComponent or JPanel, then add that to a frame, ..applet, window, JInternalFrame, dialog, constraint of a layout, part of a split pane..
Listeners
As to the listeners. Rather than traverse a huge if/else structure in the single actionPerformed() method to determine the required action, it is more optimal to either:
Create a listener for each control that needs it.
Create an instance of an AbstractAction that might be used for multiple controls ('copy' button, menu item etc.).
Summary
So (generally) for the:
JFrame, don't extend.
Listeners, create and add as needed.
Honestly, it depends on the situation. One basic rule when coding is to "code to abstract classes or interfaces".
So, in a nutshell, have a class extending (or implementing) a JFrame (or whatever interface or class) and/or have one doing the same thing with ActionListener.
It is all about the maintainability, flexibility and cleanness of your code.
Standard approach: use EventQueue in method main, that creates main form. In that case all your operations will be asynchronous
in which the main class extends JFrame
the main calss doesn't have to extend JFrame. if it doesn't you should create a JFrame object like you do with any other class
where the JFrame object is created inside the main method
If the MainClass extend JFrame it created inside the c'tor (in the super() ).
This method is supposed to merge two the definitions of two entries for a single in a glossary. It creates an instance of the GlossaryEntryMergeUI class (extension of JFrame), which walks the user through the merging process. The user clicks a button to submit and the window closes. The merge method extracts the merged definitions and returns the combined glossary entry.
What is the best way to make the merge method wait for response from the MergeUI? I tried using InvokeAndWait, but I couldn't figure out how to make it work.
public GlossaryEntry merge(GlossaryEntry otherEntry){
//First, merge the definitions
GlossaryEntryMergeUI thisMerge = new GlossaryEntryMergeUI(this,otherEntry,mergeSignal);
thisMerge.setVisible(true);
thisMerge.setAlwaysOnTop(true);
GlossaryEntry combined = new GlossaryEntry(word);
combined.addDefinitions(thisMerge.getDefinitions());
return combined;
}
consider to look for CardLayout instead of switch between two or more Windows
if is there Serializable or Observate, then better is wrap the code into invokeAndWait(), for simple switch between two Windows is there invokeLater()
I'd suggest not using two JFrames in same time, one JFrame and another Window would be JDialod or JWindow, because (for example if is there BackGroung Task) sometimes is so hard swith Focus from one JFrame to another, not to move JFrame toFront() ...
This has nothing to do with use of invokeAndWait or invokeLater and all to do with listening on one thread for a response in another. If you're not using a modal dialog for this, such as a JOptionPane (which is quite easy to use and can hold a very comnplex GUI if needed), consider using a listener or otherwise known as the observer design pattern to notify the non-GUI component when the GUI has been acted upon.
Also, is GlossaryEntryMergeUI the only GUI the user comes in contact with? Or is it called into being from another GUI, perhaps a "parent" GUI? If the latter, then a modal dialog, not a JFrame is the way to go. Edit: or a CardLayout as per mKorbel's excellent answer.