How to get values from a JPanel? - java

I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?
Also, what are some good tutorials that can help me further understand this? Thank you.

I'm guessing you mean JTextField and not TextField. Use the getText() method.
String text = yourTextField.getText();
Also works with the TextField class, actually.
You'll need an ActionListener on your submit button if you want to grab the text fields' values when a user clicks the button.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == yourButtonsName) {
text = yourTextField.getText();
}
}
Don't forget to add the ActionListener!
yourButtonsName.addActionerListener(this);
Or you could use Java 8 lambda expression:
yourButtonsName.addActionerListener(e -> text = yourTextField.getText);
If you'd like to learn more about Java's graphical capabilities, I recommend the Oracle docs: http://docs.oracle.com/javase/tutorial/uiswing/.

"I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?"
Sounds like to me you're facing the class problem of how do I reference instance variables from one, in another.
An easy way would be to pass one class as reference to another and use proper getters and setters. You can see a solution here.
A better solution though would be to create an interface that one of the classes implements and pass that class as an interface to the second class. You can see an example here.
If you feel you're ready for more advanced topics, you should look into MCV Design patterns for this type of problem. MVC is designed for multi-component interaction.

Related

Using Inner classes correctly (how to share class in user event)

I am trying to program a java application that consists of several windows using JFrame.
Each JFrame contains a JTextField and buton to go to the next JFrame.
I need to retrieve all the information entered by the user at the end.
I created an event click on the buton to save to a public class all the data that the user introduce in the JTextField. I named that public class myData, which has a static attributes.
The problem is that I can not access this class from the button listener function.
I get an error: cannot refer to an non final variable inside an inner class defined in a different method.
My goal is to be able to share the class myData between different methods of a different class.
E.g. I have a class named myClass1 and myClass2, so I want to share the myData attribute between myClass1 methods and myClass2 methods.
Please anyone can someone help me? or propose another way to do this!
Thanks in advance !
All of the calls about MVC etc. are valid, but this isn't that hard.
What you want to do is in your Main, you can create your Data (Model) class, the class that holds all of your information.
So, you can do something like this:
public class F1 ... {
private final Data myData;
public F1(Data theData) {
myData = theData;
}
....
}
public class Main {
Data myData;
public static void main(String args[]) {
Main m = new Main();
m.setMyData(new Data());
F1 f = new F1(m.getMyData());
...
}
}
Then, later, when F1 calls F2, simply do the same thing -- create F2 with the Data passed in earlier by the constructor. That way, as each Frame runs its course, they're all working on the same instance of Data. When all is done, the single instance of Data is left within the Main class for you to do with what you will.
There are better ways to reorganize your entire program, but this should give you ideas on how to get over the hump you're having right now.
Addenda:
There are several things you can do.
When your get the ActionEvent, it contains a source. That source is the component that generated the event (most likely a Button in this case). If you know where the button is located in the hierarchy of things, you get to your Frame directly. In the pastebin example, you have Frame -> Panel -> Button. So, if you have the Button, you cat get to the Frame.
public void actionPerformed(ActionEvent e) {
JButton sourceButton = (JButton)e.getSource();
F1 f1 = (F1)sourceButton.getParent().getParent();
Data myData = f1.getMyData();
data.setField(...);
}
Again, this is not the recommended ways of doing things. The tutorials have decent examples of using MVC and property change listeners and the whole kit. But this should get you to where you want to go.
Sorry, but your design needs alot of work. I'm going to recommend you read up on MVC. it may seem like alot to chew on right now but it will help you immensely in the long run. On a side note, dont nest your data class definition(s), and remember to always distinguish between classes and objects.
Your overall design of swapping JFrame's seems a bit iffy to me. Why not instead use either dialogs such as a JDialog or JOptionPane or even better a CardLayout to swap views. Also I urge you not to use static fields for any of this as this can cause significant problems in the future and makes your code less compliant with good object oriented principles. With regards to information sharing, about all I can say is that it's all about one class having the proper reference to the other class. For more specific advice you'll likely need to show us more information and code.
Edit
Also, you know of course that you can get a reference to the JButton that stimulated the ActionListener by calling getSource() on the ActionEvent object passed into the actionPerformed method. This may allow you to get a reference to the class that holds the JButton if necessary.

Saving states across JFrames

I am trying the save the state of a previous frame and then carry it over to the other frame. More like saving the data of the textfields and areas so that when i press next button some text fields,and variables will be initialized in the next forms Labels and when you press back your previous data will still remain in your form inteface.Pls help
More like data binding but across different forms
You can use any varible for that, and pass it as parameter to every JFrame you create.
But it sounds more like you want to use a CardLayout for your JFrame and use different cards that can be shown for the user. See How to use CardLayout.
If you are trying to create a wizard like UI, you should look up Sun(oracle)tutorial here.
Use something like Java's XMLEncoder.

How to switch between application's windows and communicate with the controller?

When writing a graphical interface, using Java, what's the appropriate way of switching between the different windows of the application, when clicking a button for example? I.E. what are the windows supposed to be, JPanels, JFrames...? And how do all the components 'see' the 'domain controller' (the class that links the graphical package to the application logic package)?
Any guide or reference would be appreciated.
You start your application with your Controller. In the constructor of your controller, you are going to initialize the first GUI you want to open, lets say GUI_A:
private GUI_A gui_a = null;
Controller() {
gui_a = new GUI_A(this);
}
As you might notice, I called the constructor of GUI_A with one parameter: this. this is referencing the instance of the current class, so this is type of Controller. The constructor of GUI_A has to look something like this:
private Controller controller = null;
GUI_A(Controller ctrl) {
controller = ctrl;
}
This is a simple way to get the GUI known to the Controller.
The next thing you would do is displaying GUI_A:
gui_a.setVisible(true);
If you now want to handle button-clicks, you would do it like this:
First, you add the action-performed method to your button. And, as it is best practice in MVC, you don't want to do logic in your view/GUI. So you also create a corresponding method in your Controller for the action-performed, and call it from your GUI:
// Controller
GUI_A_button1_actionPerformed(ActionEvent evt) {
// Add your button logic here
}
// GUI_A
button1_actionPerformed(ActionEvent evt) {
controller.GUI_A_button1_actionPerformed(evt);
}
Usually you don't need to pass the ActionEvent-var to the Controller, as you will not need it often. More often you would read a text out of a TextField and pass it on to your Controller:
// Controller
GUI_A_button1_actionPerformed(String text) {
// Add logic for the text here
}
// GUI_A
button1_actionPerformed(ActionEvent evt) {
controller.GUI_A_button1_actionPerformed(textField1.getText());
}
If you now want to access some fields on your GUI_A from the Controller, be sure not to mark the fields as public in your GUI, but to create public methods which handle how to display the values.
The preferable way is using Actions. You can attach action to each control. When user action happens (e.g. click on button) the appropriate Action is called. Actions can delegate calls deeper into the application logic and call graphical components (JFrams, etc).
suggestion: use tabbed-panel should do this, JPanel is just a Java container, while JFrame should be the outside windows, they are different things. there should be several JPanels on top of One JFrame. your app can have multiple JFrames.
When writing a graphical interface, using Java, what's the appropriate way of switching between the different windows of the application, when clicking a button for example?
Add an ActionListener to the button. In the actionPerformed(ActionEvent) method, do what needs to be done.
I.E. what are the windows supposed to be, JPanels, JFrames...?
I would recommend making the main window a JFrame and using either a JDialog or JOptionPane for most of the other elements. Alternately, multiple GUI elements can be added into a single space in a number of ways - CardLayout, JTabbedPane, JSplitPane, JDesktopPane/JInternalFrame, ..
And how do all the components 'see' the 'domain controller' (the class that links the graphical package to the application logic package)?
One way is to pass a reference to the object between the UIs.

Java Multiple Input Dialog

I have a Java application and I want to open a new dialog from the main interface where the user can enter his name, surname and country and then click ok. How can I open a dialog which has a number of different input fields and then save that information in a variable?
Extend JDialog and add some JTextFields and maybe some JComboBoxes. then finish it off with some JButtons.
You could also look into JGoodies Forms framework; it's nice and free.
EDIT: Composition example
Based on Pete's comment I dug up this example using composition rather than overriding JDialog.
You would want to add getter like
public String getFirstName() {
return field.getTest();
}
To gain access to relevant input.
This forum post could be helpful.
One possibility to make a custom
JDialog is to create a custom JPanel
with all the bells and whistles that
you need and use that as the Component
in one of the static JOptionPane
functions.
With java and swing you have to write some code. I build a library which creates a dialog with different inputs in a few lines. It's called UiBooster.
FilledForm form = new UiBooster()
.createForm("Personal informations")
.addText("Whats your first name?")
.addTextArea("Tell me something about you")
.addSelection(
"Whats your favorite movie?",
Arrays.asList("Pulp Fiction", "Bambi", "The Godfather", "Hangover"))
.show();

Link Java textbox to string in external class

I am currently working on a project in which I have a Java GUI class and another class which contains its relevant methods.
I want a text area in the GUI to be updated with the content of a string in the other class whenever it changes. What is the easiest way to watch for these changes?
Cheers!
You're looking for data binding. Java unfortunately has no own support for that, but there are several libraries to choose from, like for example JGoodies data binding.
If you want to roll your own, there's the ubiquitous observer pattern which you doubtless already know from Swing :). Just add listener support to the class holding the strings and add a listener to it that updates the text area, when an event comes.
Make the "other class" a proper bean that supports PropertyChangeListeners. Then create a PropertyChangeLister which acts on changes in the "other class" and which updates the textarea.
Something like this:
otherClass.addPropertyChangeListener("propertyname", new PropertyChangeListener() {
void propertyChange(PropertyChangeEvent evt) {
textarea.setText(evt.getNewValue());
}
}
See
https://docs.oracle.com/javase/1.5.0/docs/api/java/beans/PropertyChangeListener.html
https://docs.oracle.com/javase/1.5.0/docs/api/java/beans/PropertyChangeSupport.html
http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html
Have a look at BeansBinding
It does almost exactly what you need. Only thing is that your otherClass must support Java Beans listeners, as described by #ordnungswidrig

Categories