Unable to get values from another jFrame - java

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.

Related

Is there anything logically wrong with creating a JFrame then using dispose() and then another JFrame and so on

Ok so, whilst my code works. I am beginning to question the logic of my code, and how I can improve it, before adding yet more code.
In short, I am creating a JFrame using Borderlayout as the layout manager. I have added a JPanel, which then has buttons, textfields etc added. Once the user has done everything they need to do, I get the user to click "ok" and I basically call the dispose() method.
I then paint a new JFrame, and do exactly the same thing repeatedly.
Whilst this is easy to code, and I'm a self taught newb, I am concerned about my lack of code re-use and I am convinced I should only be using one JFrame.
My main question is this : Is the dispose() method destroying the window, or just hiding it?
Any advice on this topic, would be much appreciated :)

GUI - Switching between screens

I got my program, that can connect to a Database working! ( Hooray )
But now, I ran into a new problem. I read that using multiple JFrame windows (and closing the old one) is not user friendly, and a bad learning habit.
So now I am wondering, is there a way to switch between Panels, or something similar?
Example:
JFrame with Login & Password. -- Users logs in, goes to the next 'screen' where he or she can see the Database info, cause he or she logged in!
What should I use, any good methods out there?
you may want to check CardLayout
The simple answer is yes you can. The idea is to have a localized class that contains a method that outside classes can call passing a jPanel then simply add that panel to your jFrames content pane (which in turn will remove the other panel). There are many ways to go about this and I hope you find one that works and I hope this answer helps you as well.
Here is the procedure I generally follow. I create and open a new Frame and make the parent frame invisible. Again when child frame is closed I make the parent frame visible. I am using this procedure for a long time and not facing any problem.
This is the piece of the code executed when login button is clicked.
...
setVisible(false); //Hide the login page
DBPage page=new DBPage(this, value1); // DBPage is another JFrame
page.setVisible(true);
I feel this much of code is enough to understand.
JLayeredPane might work.
http://docs.oracle.com/javase/8/docs/api/javax/swing/JLayeredPane.html
You could have several layers on top of each other, the login screen, etc. and show the layer that is most relevant at the time.
A previous question may prove useful:
Java Swing - how to show a panel on top of another panel?

how to reuse a jframe without making it new?

I was wondering if there was a way to reuse a jframe without making it new. You might be wondering why. I have two JFrames (actually more, but for this question's purpose, two). One contains a radio button(agree) with the terms and conditions written in a jtextarea. THe other JFrame contains a passwordtxtarea(password), jtextarea(username) and a radio button(read terms and conditions), as well as a "TermsAnd Conditions" button.I forgot to mention that the first jtextarea contains a "back" jbutton, that if i press on, I get JFrame2, when I press "Terms And Conditions", I get JFrame1. The problem is, that my code requires both "Agree" and "read the Terms" radio buttons to be clicked on, but whenever I press "back" or "Terms And Conditions", any input I had put in (username, password, clicks on radio button other than default) is lost. Therefore I cannot proceed in my program.
I think it has to do with the fact that I have to make a NEW JFrame Form. Maybe it sets it back to default? Anyway, how do I fix this problem? I haven't seen a question like this, so is there a blatantly obvious answer I'm unable to see, except for "it's impossible"?
You state/and I reply:
I was wondering if there was a way to reuse a jframe without making it new.
Yes, it is quite possible to re-use components (the generalization of your question).
You might be wondering why. I have two JFrames (actually more, but for this question's purpose, two).
As has been stated, this is generally not a goood idea. Most Swing GUI applications use only one main window, the JFrame, and then either swap views such as with CardLayout or JTabbedPane, or show modal or non-modal dialog windows.
One contains a radio button(agree) with the terms and conditions written in a jtextarea. THe other JFrame contains a passwordtxtarea(password), jtextarea(username) and a radio button(read terms and conditions), as well as a "TermsAnd Conditions" button. I forgot to mention that the first jtextarea contains a "back" jbutton,
It's most unusual for a JTextArea to have a button of any kind. Also, there is no such thing as a "passwordtxtarea", perhaps you mean JPasswordField? If so, please be precise with your terms when asking questions here. It's hard enough to guess what someone's program is like based on a description, that you don't want to make it harder on us. Also, it's very unusual to use a JTextArea for a user name field, since usually you'd use a JTextField. Again, precision really matters. Else we'll likely give you the wrong advice.
that if i press on, I get JFrame2, when I press "Terms And Conditions", I get JFrame1. The problem is, that my code requires both "Agree" and "read the Terms" radio buttons to be clicked on, but whenever I press "back" or "Terms And Conditions", any input I had put in (username, password, clicks on radio button other than default) is lost. Therefore I cannot proceed in my program.
Yes, you should not be creating new components here but rather re-using previously created components. It's all do-able if you make your component a class field and if you make sure to create it only once. It's all how you code it.
I think it has to do with the fact that I have to make a NEW JFrame Form. Maybe it sets it back to default? Anyway, how do I fix this problem? I haven't seen a question like this, so is there a blatantly obvious answer I'm unable to see, except for "it's impossible"?
Again it's possible. The solution will all depend on the structure of your program.
A word of advice: gear your GUI code toward making JPanels, not JFrames. This way you can place them anywhere they are needed -- in a JFrame, a JDialog, another JPanel, or swapped with a CardLayout,... anywhere. It greatly increases the flexibility of your program.

Java/Swing - how to reduce size of JDialog constructor?

I am building a graphical user interface in Java and I was wondering if anyone can give me some directions.
Specifically, When clicking on a button in this GUI a big JDialog (it's a class that extends a JDialog) opens up for the user to enter some information, see some information, click on some things etc.
This class has multiple JLabels and other components in it. My question is how would one create such an instance? Right now I have everything in the constructor, making it a 500(!) lines constructor. There has to be an alternative to that!
The constructor is about 300 lines of code of components placement and settings for them and another 200 lines for the listeners give or take.
Also another question that comes in mind is that right now I open this window from another class by calling
MyClassExtendsJDIalog temp = new MyClassExtendsJDIalog();
but I don't use this "temp" variable at all in the class that I create it, as the constructor of "temp" does EVERYTHING. It seems like I am, again, doing something the wrong way.
Thanks for reading this.
If you want split up the code to make it more readable and manageable you can allways group the fields into subclasses of JPanel, i.e. Panel1, Panel2 etc and then just add those in the JDialog subclass constructor. But setting up a GUI in swing takes a lot of lines, yes...
as for the temp variable not being used, I'm guessing you call show() in the constructor?
Normally I would not do that, but instead call it in the code creating the dialog, ie.
MyDialog dialog = new MyDialog();
dialog.setVisible(true);
Without seeing your code it's difficult to give you specific tips on how to improve your code and design.
I agree, ~500 lines in your constructor intuitively feels like a problem. At a minimum, you might want to defer some of that work until after the instance has been created. Moving this into a init() method (or series of methods) is one approach.
You also might want to consider designing your class such that it contains a JDialog instead of extending one (See Composition over inheritance for a discussion on this topic) I suspect otherwise you are conflating the concerns of several classes.
Finally, you might want to review the Java Swing Tutorial for general tips and techniques for creating Swing based user interfaces.
Yes you are doing something wrong, but you are in good (or bad) company.
You should apply the rules of good OO design and clean code to your swing classes as to anything else.
What exactly you can do is hard to tell without looking at the 300+ lines of code (and I really don't want to see the ;-) but here are somethings that are probably applicable.
My main design rule is the Single Responsibilite Principle. According to your description (and my guesswork), you are doing the following in your constructor:
* creating (including configuring) components
* placing them in some kind of layout
* registering Listeners
* implementing Listners
These are 4 completely different concerns.
After some heavy refactoring you might end up with something like this:
You might want to have a factory that creates your components.
You might have a Layouter class that takes a component or a group of components (like label plus matching textbox) and places them on a panel.
You might have a class takes components (and maybe models or whatever) and wires them together using Listeners.
And a class that gets passed all this uses it in a suitable way and spits out a JDialog with the panel with all your components on.
Note: Idealy nothing extends JDialog anymore. You should only extend Janything if you intend to build a new Swing component.
This example is using Scala but it still should offer some inspiration: http://blog.schauderhaft.de/2011/06/26/clean-code-with-swing-and-scala/

How to use setVisible in JFrames?

In my program I have two JFrame instances. When I click next button I want to show next frame and hide current frame. So I use this.setVisible(false) and new Next().setVisible(true). But in Next window if I click back button I want to set previous frame to be visible again and next frame must be ended (which means it must be exited).
Is there any special method(s) to do this? How can I do it?
Consider using CardLayout instead of hunting for how many JFrames there are. Then..
only one JFrame would be needed
any of Next/Back Actions will be only switching between cards
There are lots of examples in this forum - e.g. as shown here.
That is an odd & quirky GUI. I suggest instead to run a JFrame for the main GUI, and when the user wants to search, pop a JOptionPane (or modal JDialog) to accept the details to search for. This will not have the effect described above, but will follow the 'path of least surprise' for the end user.
If you want to destroy a JFrame releasing all associated resources you shold call dispose() method on it.
You may place your JFrames on a list data structure and keep a reference to current position according to the window you are displaying. In that way it will be easy to move to next and previous. But note that each frame added to the list will use memory and will have its state as you placed it in to the list.
If you are trying to create a wizard like UI, you should look up Sun(oracle)tutorial here.
create the instance of your main window in next() window.. and use same method which you chosed befoe to hide your main window, for example if your main window is named as gui then what we have to do is.
gui obj = new gui();
and if you click on back button now than do these also
this.setVisibility(false);
obj.setVisibility(true);
that's all you need.
good luck.

Categories

Resources