Throwing a value to the other class - java

Can you help me with this?
Here is the code first:
public RegistrationForm(){
super("Registration Form (Assignment One)");
setLayout(new GridLayout(6,2));
l[0] = new JLabel("Name: ");
l[0].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[0]);
tf[0] = new JTextField();
tf[0].setToolTipText("Enter Your Full Name");
add(tf[0]);
l[1] = new JLabel("Age: ");
l[1].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[1]);
tf[1] = new JTextField();
tf[1].setToolTipText("Enter Your Age");
add(tf[1]);
l[2] = new JLabel("Birthday: ");
l[2].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[2]);
tf[2] = new JTextField();
tf[2].setToolTipText("Enter Your Birthday");
add(tf[2]);
l[3] = new JLabel("Address: ");
l[3].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[3]);
tf[3] = new JTextField();
tf[3].setToolTipText("Enter Your Address");
add(tf[3]);
l[4] = new JLabel("Contact Number: ");
l[4].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[4]);
tf[4] = new JTextField();
tf[4].setToolTipText("Enter Your Contact Number");
add(tf[4]);
b[0] = new JButton("Submit");
b[0].addActionListener(this);
add(b[0]);
b[1] = new JButton("Clear");
b[1].addActionListener(this);
add(b[1]);
}
So When I input a value to all and press "Submit" the previous class will close and another class will open and there it will show the value of the things I inputted from the previous class. . .
There is no default value to JTextfields, I'm going to enter the value myself.
How can i throw(I mean pass) a value to the other class?
Here is the code i have so far:
This is my method:
public String name(){
return tf[0].getText();
}
This is from my Other class:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}

You don't need to throw anything. Whatever class that displays this dialog will hold a reference to the instance of this class and can simply query the state of the fields once the dialog returns. This is much easier if the dialog window is a modal dialog such as a modal JDialog or a JOptionPane.
For instance, please look at my code in this example.
Edit
Also, this confuses me:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}
Does this code display the RegistrationForm object? Is RegistrationForm in fact a modal JDialog? It is very unusual to extract a JTextField from one GUI and add it to another, and I'm pretty sure that you don't want to do this. Again, what you want to do is:
Display your RegistrationForm as a modal JDialog.
After it returns, call getter methods on the RegistrationForm object that extracts the Strings held by the text fields of the object.
For more details, you'll still need to tell us a lot more about your code and your problem.

Related

How to plus 2 JTextField numbers?

I want to add two numbers and put the result into a JTextFields (textboxes). Why doesn't this code work?
public class Window extends JFrame implements ActionListener {
private JButton plus;
private JLabel text;
private JTextField textbox1;
private JTextField textbox2;
public Okno(){
this.setLayout(new FlowLayout());
this.setBounds(400,400,400,400);
plus = new JButton("+");
text = new JLabel("");
plus.addActionListener(this);
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
this.add(text);
this.add(textbox1);
this.add(textbox2);
this.add(plus);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(plus)){
int result = Integer.valueOf(textbox1.getText()) + Integer.valueOf(textbox2.getText());
text.setText(Integer.toString(result)); //gtregergregergergreg
}
}
}
Thank you for your help.
It works, if you remove spaces while putting numbers to the text fields, otherwise you get NumberFormatException. By the way don't use spaces for aligning the text fields. You can use setColumns or different layout manager. Also you should validate input to be sure there are just numbers, if you want to add them together.
Delete spaces from:
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
cause while parsing to Integer it fails.
Set prefered size of textbox1 and textbox2:
textbox1 = new JTextField();
textbox1.setPreferredSize(new Dimension(20,20));
textbox2 = new JTextField();
textbox2.setPreferredSize(new Dimension(20,20));
Hope I helped :)

get values of Jtextfields when click OK in Dialog

My need is to display a tab in a JDialog (confirmDialog or inputDialog). The tab contains 2 JTextField per row. The display works fine :
but I don't know how to get the values of the JTextFields.
Here is the display code :
int size = model.getCheckedApplications().size();
// une ligne par application sélectionnée
layout = new GridLayout(size + 1, 3, 5, 5);
myPanel = new JPanel(layout);
myPanel.add(new JLabel("Application"));
myPanel.add(new JLabel("Version cadre"));
myPanel.add(new JLabel("Nouvelles natures"));
for (Application app : model.getCheckedApplications()) {
myPanel.add(new JLabel(app.getCode88()));
JTextField versionActuelleField = new JTextField(30);
versionActuelleField.setName("versionActuelle"
+ app.getCode88());
versionActuelleField.setText(app
.getVersionCadreActuelle());
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
myPanel.add(versionActuelleField);
myPanel.add(nouvellesNaturesField);
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then I don't know how to get the values when the user clicks on the OK Button :
if (result == 0) { // The user clicks on the ok button
You need to add them to some list that you store, so you can get at them again. Since you are adding them in reference to an application, I would suggest a Map
private Map<Application, JTextField> nouvellesNaturesFields = new ArrayListMultimap<Application, JTextField>(); //Or Hashmap, if the key is unique
private Map<Application, JTextField> versionActuelleFields = new ArrayListMultiMap<Application, JTextField>();
public List<JTextField> getNouvellesNaturesFields() {
return nouvellesNaturesFields ;
}
public List<JTextField> getVersionActuelleFields () {
return versionActuelleFields ;
}
//class code
for (Application app : model.getCheckedApplications()) {
//Other code
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
nouvellesNaturesFields.put(app, nouvellesNaturesField);
//Other code and same for your new nature fields
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then when the user clicks the confirm button, using the property accessor getNouvellesNaturesFields()or getVersionActuelleFields() you can iterate all the fields created, like so:
for (Map.Entry<Application, JTextField> entry: myMap.entries()) {
//Do something here
}
Or you could also get them via:
for (Application app : model.getCheckedApplications()) {
List<JTextField> data = myMap.get(app);
for(JTextField field : data) {
field.getText();
}
}
Since the key value probably won't be unique, I used an ArrayListMultiMap, but if it would be unique, then a HashMap should suffice
You assign the Jtextfield value to a string using the getText() method e.g below
String texfield = JTextField.getText();
Subsequently you use the String textfield wherever you want. And to get the right jtextfield you have to get text from the textfield you want for example you have four Jtexfield. Assuming they are JTextField1, JTextField2, JTextField3 and JTextField4. To get the value of JTextField3 you have
String texfield = JTextField3.getText();
The values should be in the JTextFields you created:
versionActuelleField
nouvellesNaturesField
Also, you might want to look at ParamDialog, which I implemented to be a generic solution to this question.
EDIT
Yes I see now that you are creating these JTextFields in a loop. So you need to create a Collection, I'd suggest a Map<String, JTextField> where you could map all of your application names to the matching JTextField, as well as iterate over the collection to get all application names / JTextFields.

Trying to Display text input in a java a JFrame window [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm using JCreator Pro. I'm trying to get information entered in the textfields to display and calculate the selling price of used cars. The window looks like this:
When I click display, I want the information to appear on the bottom half of the window (car make and model, year of manufacturing, sale price)
But when I do click it, all I get are these lines of text in the General output window and I can't make out what's wrong. My code compiles without any errors.
Here's my main class for reference:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MIT141674CarDetailsTest extends JFrame implements ActionListener {
MIT141674Car car;
JTextField jtfMakeModel, jtfYear, jtfPurchPrice;
JButton jbtnDisplay, jbtnClear;
JLabel jlblMakeModel, jlblYear, jlblSellPrice;
public MIT141674CarDetailsTest() {
setSize(500, 210);
setLocationRelativeTo(null);
setTitle("Purchased car details");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(7, 2));
// input
add(new JLabel(" Enter car make and model: "));
jtfMakeModel = new JTextField();
add(jtfMakeModel);
add(new JLabel(" Enter year of manufacturing: "));
jtfYear = new JTextField();
add(jtfYear);
add(new JLabel(" Enter purchase price: "));
jtfPurchPrice = new JTextField();
add(jtfPurchPrice);
// buttons
jbtnDisplay = new JButton("Display");
add(jbtnDisplay);
jbtnDisplay.addActionListener(this);
jbtnClear = new JButton("Clear all");
add(jbtnClear);
jbtnClear.addActionListener(this);
// display car
add(new JLabel(" Car make and model: "));
jlblMakeModel = new JLabel("");
add(jlblMakeModel);
add(new JLabel(" Year of manufacturing: "));
jlblYear = new JLabel("0000");
add(jlblYear);
add(new JLabel(" Sale price: "));
jlblSellPrice = new JLabel("$0.00");
add(jlblSellPrice);
}
public static void main(String[] args) {
MIT141674CarDetailsTest carWin = new MIT141674CarDetailsTest();
carWin.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("Display")) {
int carYear = Integer.parseInt(jtfYear.getText());
if (carYear >= 2009) {
double pPrice = Double.parseDouble(jtfPurchPrice.getText());
if (pPrice > 0) {
car = new MIT141674Car(jtfMakeModel.getText(),
carYear, pPrice);
jlblMakeModel.setText(car.getMakeModel());
jlblYear.setText(Integer.toString(car.getYear()));
jlblSellPrice
.setText(Double.toString(car.getSellingPrice()));
} else
// pPrice <=0 - invalid
JOptionPane.showMessageDialog(null,
"Invalid purchase price, please re-enter");
} // carYear <=2009
else
// invalid carYear
JOptionPane.showMessageDialog(null,
"Invalid year of manufacturing, please re-enter");
} // if display
else
// not Display button, then check if it's Clear all button
if (str.equals("Clear all")) {
// remove text from all text fields
jtfMakeModel.setText("");
jtfYear.setText("");
jtfPurchPrice.setText("");
// clear labels
jlblMakeModel.setText("");
jlblYear.setText("0000");
jlblSellPrice.setText("$0.00");
}
} // actionPerformed
} // end of class
Can anyone help me and tell me what is wrong?
EDIT: I have partially solved my problem by doing what #Exbury mentioned by changing
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);
But now I've found that the year entered only displays if I enter 2009, any other years entered after 2009 comes up as 0.
Giving one class a getter/accessor method that extracts the desired information of JTextField and giving the other class a setter/mutator method that allows outside objects to inject the desired information, here to set the text of its JLabel
While creating car object you are using same car reference (null) in constructor
Change this to
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());`
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);

Writing actionListner to display form input on console upon confirmation

I am currently constructing a GUI which allows me to add new cruises to the system. I want to write an actionListner which once the user clicks on "ok" then the form input will be displayed as output on the console.
I currently have the following draft to complete this task:
ok = new JButton("Add Cruise");
ok.setToolTipText("To add the Cruise to the system");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int selected = typeList2.getSelectedIndex();
String tText = typeList2[selected];
Boolean addtheCruise = false;
addtheCruise = fleet.addCruise();
fleet.printCruise();
if (addtheCruise)
{
frame.setVisible(false);
}
else
{ // Report error, and allow form to be re-used
JOptionPane.showMessageDialog(frame,
"That Cruise already exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
buttonPanel.add(ok);
Here is the rest of the code to the Form input frame:
contentPane2 = new JPanel (new GridLayout(18, 1)); //row, col
nameInput = new JLabel ("Input Cruise Name:");
nameInput.setForeground(normalText);
contentPane2.add(nameInput);
Frame2.add(contentPane2);
Cruisename = new JTextField("",10);
contentPane2.add(Cruisename);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
confirmPanel = new JPanel ();
confirmPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
confirmPanel.setBorder(BorderFactory.createLineBorder(Color.PINK));
addItinerary = new JButton("Add Itinerary");
confirmPanel.add(Add);
confirmPanel.add(addItinerary );
Frame2.add(confirmPanel, BorderLayout.PAGE_END);
Frame2.setVisible(true);
contentPane2.add(Cruisename);
Frame2.add(contentPane2);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
contentPane2.setBorder(BorderFactory.createLineBorder(Color.black));
//Label for start and end location jcombobox
CruiseMessage = new JLabel ("Enter Start and End Location of new Cruise:");
CruiseMessage.setForeground(normalText);
contentPane2.add(CruiseMessage);
Frame2.add(contentPane2);
/**
* creating start location JComboBox
*/
startL = new JComboBox();
final JComboBox typeList2;
final String[] typeStrings2 = {
"Select Start Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
startL = new JComboBox(typeStrings2);
contentPane2.add(startL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
/**
* creating end location JComboBox
*/
endL = new JComboBox();
final JComboBox typeList3;
final String[] typeStrings3 = {
"Select End Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
endL = new JComboBox(typeStrings3);
contentPane2.add(endL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
//Label for select ship jcombobox
selectShipM = new JLabel ("Select Ship to assign Cruise:");
selectShipM.setForeground(normalText);
contentPane2.add(selectShipM);
Frame2.add(contentPane2);
/**
* creating select ship JCombobox
* select ship to assign cruise
*/
selectShip = new JComboBox();
final JComboBox typeList4;
final String[] typeStrings4 = {
"Select Ship", "Dalton Princess", "Stafford Princess" };
selectShip = new JComboBox(typeStrings4);
contentPane2.add(selectShip);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
I need all form inputs from the code above to be displayed on the console upon completion.
Summary:
1. I have two ships in one fleet
2. To add new cruise, all fields (Name, start date, end date, ship) must be selected.
The Problem:
1. I keep coming up with errors when creating " fleet = new Fleet();" in my constructor. Even though I have declared it in my class.
2. In the draft code below, line 5 states "typeList2", however, I have two JComboBox's - two different type Strings for both drop down menu's (Shown in the rest of the code). How do I input both typeLists to the output rather than just one?
Thank you.

Values user inputs into a GUI are not saving?

Below is the code I am working on. Basically I need a box to open and get the user to input their data in the corresponding text fields. All is working great. Everything is outputting correctly when I print it from the actionPerformed method, but when I call gui.displayPersonInfo method from main it shows all of the values as null. It is doing the displayPersonInfo method first before the box has even opened, even though I call the method after. Anyone know what is wrong with my code? (output below)
package userInput;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Person extends JFrame{
String Name;
String Address;
String PhoneNumHome;
String PhoneNumWork;
String email;
JLabel label, label2;
JTextField tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8;
JButton button;
public Person(){
setLayout(new FlowLayout());
label = new JLabel("Enter your name");
add(label);
tf1 = new JTextField(10);
add(tf1);
label = new JLabel("Enter your Address (street number + street name)");
add(label);
tf2 = new JTextField(10);
add(tf2);
label = new JLabel("Enter your city");
add(label);
tf3 = new JTextField(10);
add(tf3);
label = new JLabel("Enter your province");
add(label);
tf4 = new JTextField(10);
add(tf4);
label = new JLabel("Enter your postal code");
add(label);
tf5 = new JTextField(10);
add(tf5);
label = new JLabel("Enter your home phone number (306-xxx-xxx)");
add(label);
tf6 = new JTextField(10);
add(tf6);
label = new JLabel("Enter your work phone number (306-xxx-xxx)");
add(label);
tf7 = new JTextField(10);
add(tf7);
label = new JLabel("Enter your email (user#emailservice.xxx");
add(label);
tf8 = new JTextField(10);
add(tf8);
button = new JButton("Next");
add(button);
event e = new event();
button.addActionListener(e);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
String address1, pnum, wnum, a;
try{
String word = tf1.getText();
Name = word;
System.out.println(Name);
Address = tf2.getText();
Address = Address + " " + tf3.getText();
Address = Address + " " + tf4.getText();
Address = Address + " " + tf5.getText();
address1 = Address;
System.out.println(Address);
PhoneNumHome = tf6.getText();
pnum = PhoneNumHome;
PhoneNumWork = tf7.getText();
wnum = PhoneNumWork;
email = tf8.getText();
a = email;
System.out.println(PhoneNumHome);
System.out.println(PhoneNumWork);
System.out.println(email);
saveInfo(word, address1, pnum, wnum, a);
displayPersonInfo();
System.exit(0);
}catch(Exception ex){}
}
}
public void displayPersonInfo(){
System.out.println("Name: " + Name);
System.out.println("Address: " + Address);
System.out.println("Home Phone Number: " + PhoneNumHome);
System.out.println("Work Phone Number: " + PhoneNumWork);
System.out.println("Email: " + email);
}
public void saveInfo(String name, String address, String Hphone, String Wphone, String Email){
Name = name;
Address = address;
PhoneNumHome = Hphone;
PhoneNumWork = Wphone;
email = Email;
}
public static void main(String[] args) {
Person gui = new Person();
gui.displayPersonInfo();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Enter Information");
gui.setSize(350,330);
gui.setLocation(500,250);
gui.setVisible(true);
}
}
here is the output: (it acts as if displayPersonInfo occurs first)
run:
Name: null
Address: null
Home Phone Number: null
Work Phone Number: null
Email: null
A Name (now it prints it from within actionPerformed)
An Adress a City a province a postal code
a number
another number
an email
Name: A Name
Address: An Adress a City a province a postal code
Home Phone Number: a number
Work Phone Number: another number
Email: an email
BUILD SUCCESSFUL (total time: 20 seconds)
It seems your saveInfo function is redundant since you already set every value prior to calling it, but I don't know why saveInfo is nulling the values. Try to call displayPersonInfo before saveInfo and see what happens.
In the main method the "displayPersonInfo()" method is being called right on start. You declared the string name as a field up there uninitialized, so by default its value is null. You initialize this variable inside the actionPerformed() method inside the event class.
The problem is:
public void displayPersonInfo() {
System.out.println("Name: " + Name);
}
public static void main(String[] args) {
Person gui = new Person();
gui.displayPersonInfo();
}
You attribute the value that you want for the variable ONLY when the action is performed, so if you try to access that variable before that you will the get the default value up there, which is null. And that's exactly what you're doing. When the main method starts, it calls the displayPersonInfo(), and inside of that you try to access the variable name and it returns to you null, because the variable only receives the value that you want when the action is performed.
So the solution would be:
public void displayPersonInfo() {
String word = tf1.getText();
Name = word;
System.out.println("Name: " + Name);
}
You must give the value that you want before you call the variable. The same applies to the other ones. If you declare something as "String Name;" and try to call it, you will receive null.

Categories

Resources