Values user inputs into a GUI are not saving? - java

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.

Related

Calling specific methods between classes

Help! I dont know much about java but im trying to create a small program where people can buy items and the stock should update depending on their purchase. I have 2 different classes but what im trying to do is that i want to get the amount of items the user purchases from one class and use that number to update the stock in another class - Here is the section of my code in which i am struggling with
Code for Purchasing Item
public class PurchaseItem extends JFrame implements ActionListener {
JTextField ItemNo = new JTextField(5); //Adds a text field named ItemNo
JTextField AmountNo = new JTextField(5); //Adds a text field named AmountNo
TextArea information = new TextArea(6, 40); //Adds a text area named Information
TextArea reciept = new TextArea (10,50); //Adds a text area named Reciept
JButton Check = new JButton("Check"); //Adds a button named Check
JButton Buy = new JButton("Buy"); //Adds a button named Buy
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //For output to display in decimal and pounds format
public PurchaseItem() { //PurchaseItem class
this.setLayout(new BorderLayout()); //Adds a new layout for PurchaseItem
JPanel top = new JPanel(); //JPanel is a a container for other components
top.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
JPanel bottom = new JPanel(); //JPanel is a a container for other components
bottom.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
bottom.add(Buy); //Insert the "Buy" JButton on the frame
this.add(bottom, BorderLayout.SOUTH); //Button goes at the bottom of the frame
setBounds(100, 100, 450, 250); //Sets the bounds of the frame
setTitle("Purchase Item"); //Sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //Default option to exit frame is through button and not X sign
top.add(new JLabel("Enter Item Key:")); //Add a new JLabel at the top of the frame
top.add(ItemNo); //Set the ItemNo Text Field at the top of the frame
top.add(new JLabel ("Enter Amount:")); //Add a new JLabel at the top of the frame
top.add(AmountNo); //Set the AmountNo Text Field at the top of the frame
top.add(Check); //Set the Check Button at the top of the frame
Buy.setText("Buy"); Buy.setVisible(true); //Makes the text of the Buy Button visible
Check.addActionListener(this); //Add an ActionListener to the Check Button
Buy.addActionListener(this); //Add an ActionListener to the Buy Button
add("North", top);
JPanel middle = new JPanel(); //JPanel is a a container for other components
middle.add(information); //Set the Information Text Area at the middle of the frame
add("Center", middle);
setResizable(false); //Makes the frame not resizeable
setVisible(true); //Makes the frame visible
}
#Override //Overrides the method of the PurchaseItem class to identify mistakes and typos
public void actionPerformed(ActionEvent e) { //actionPerformed class. This is called when the actionListener event happens
String ItemKey = ItemNo.getText(); //String for getting the user input from the ItemNo Text Field
String ItemAmount = AmountNo.getText(); //String for getting the user input from the AmountNo Text Field
String Name = StockData.getName(ItemKey); //String for getting the name of the item from StockData
int Amount = Integer.parseInt(ItemAmount); //Convert String ItemAmount into an Integer variable named Amount
int NewStock = StockData.getQuantity(ItemKey) - Amount; //Integer named NewStock. NewStock is the current stock(from StockData) minus the Amount
double Total = Amount * StockData.getPrice(ItemKey); //Double named Total. Total is the Amount multiplied by the price of the item(from StockData)
Calendar cal = Calendar.getInstance(); //Calendar named cal. getInstance is used to get the current time
SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yyyy"); //SimpleDateFormat named Date. It is used to display the date
SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss"); //SimpleDateFormat named Time. It is used to display the time
if (Name == null){ //If the Name is invalid and has no return value
information.setText("There is no such item"); //Display the message on the Information Text Area
}
else if (Amount > StockData.getQuantity(ItemKey)) { //Else if the Amount(User Input) is more than the quantity of the item(from StockData)
information.setText("Sorry there is not enough stock available"); //Display the message on the Information Text Area
}
else { //Otherwise
information.setText(Name + " selected: " + Amount); //Add the Name and the Amount of the item on the Information Text Area
information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey))); //On a new line add the individual price of the item on the Information Text Area in a pound format(£)
information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey)); //On a new line add the current quantity available according to StockData on the Information Text Area
information.append("\nNew Stock After Sale: " + NewStock); //On a new line add the NewStock on the Information Text Area
information.append("\n\nTotal: " + Amount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On two new lines add the Amount plus the item price(from StockData). This becomes the Total
information.append("\n= " + pounds.format(Total)); //On a new line display the Total in a pounds format(£) on the Information Text Area
}
if (e.getSource() == Buy) { //If the user clicks the Buy Button
int response = JOptionPane.showConfirmDialog(null, "Buy " + Amount + " Units" + " for " + pounds.format(Total) + "?"); //Show a confirm dialog asking the user to confirm the purchase with a Yes, No, or Cancel option
if (response == JOptionPane.YES_OPTION) { //If the user clicks Yes on the confirm dialog
JFrame frame2 = new JFrame(); //Add a new JFrame called frame2
TextArea Reciept = new TextArea ("Receipt For Your Purchase", 20,40); //Add the Receipt Text Area onto frame2 and show the message
Reciept.append("\n\nTime: " + Time.format(cal.getTime())); Reciept.append("\nDate: " + Date.format(cal.getTime())); //On seperate lines add the Time and the Date (from Calendar)
Reciept.append("\n\nYou Have Purchased The Following Item(s): "); //Display the message
Reciept.append("\n\n" + Name + "\n" + Amount + " Units" + "\n" + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On a line add the Name and Item Amount followed by the item price (from StockData) on a new line
Reciept.append("\n\n\n" + Amount + " Unit(s)" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each" + "\nTotal = " + pounds.format(Total)); //After 3 lines display the Item Amount and the item price on the same line. On a new line display the Total in a pounds format
Reciept.append("\n\n\nThank You For Your Purchase" + "\n\nGoodbye :)"); //Show a message on two seperate lines
frame2.pack(); frame2.setSize(375, 380); frame2.setLocation(250, 250); ;frame2.setTitle("Receipt"); //Sets the size, the location, and the title of frame2
frame2.setVisible(true); frame2.setResizable(false); //sets frame2 so that it is visible and not resizable
frame2.add(Reciept); //Display the Reciept Text Area on frame2
frame2.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
}else{ //Otherwise
if (response == JOptionPane.NO_OPTION){ //If the user clicks No or Cancel on the confirm dialog
//Do nothing
}
}
Code for Checking Stock
public class CheckStock extends JFrame implements ActionListener {
JTextField stockNo = new JTextField(7); //adds a text field for user input
JTextField AmountNo = new JTextField(5);
TextArea information = new TextArea(6, 40); //adds a text area for the output
JButton check = new JButton("Check Stock"); //adds a button with the text "Check Stock"
JButton Clear = new JButton();
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //for output to display in decimal and pound format
public CheckStock() { //"CheckStock" class
setLayout(new BorderLayout()); //adds a new frame for "CheckStock"
setBounds(100, 100, 450, 220); //sets the size and location of the frame
setTitle("Check Stock"); //sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //user has to click on "Exit" button instead of X sign
check.addActionListener(this); //adds an action listener for the "check" button so when clicked by user, "actionPerformed" class is called
JPanel top = new JPanel(); //JPanel is a a container for other components. It is used at the top of the frame
add("North", top);
top.add(new JLabel("Enter Item Key:")); //adds a label at the top of tne frame
top.add(stockNo); //adds the "stockNo" text field to the top of the frame
top.add(check); //adds the "check" button to the top of the frame
JPanel middle = new JPanel(); //JPanel is a a container for other components. It is used at the middle of the frame
add("Center", middle);
middle.add(information); //in the middle of the frame, add the "information" text area
setResizable(false); //frame is not resizable
setVisible(true); //frame is visible
}
public void actionPerformed(ActionEvent e) { //this code is fired once the user runs the ActionListener
String key = stockNo.getText(); //string named "key" for the stockNo
String name = StockData.getName(key); //string named "name" for the stockData
int Quantity = StockData.getQuantity(key);
int NewStock;
if (name == null) { //if there is no input in the text field
information.setText("Enter Item Key"); //display the message on the text area
}
else if (e.getSource() == check) {
StockData.getQuantity(key);
information.append( "" + StockData.getName(key));
information.append("\n New Stock: " + StockData.getQuantity(key)); //otherwise
information.setText(name); //display the name of the item
information.append("\nPrice: " + pounds.format(StockData.getPrice(key))); //display the price of the item using pound format
information.append("\nPrevious Stock: " + Quantity); //display the amount in stock for the item according to StockData
}
}
}
You didn't initialise the object Update: your line of code should be
PurchaseItem Update = new PurchaseItem();
(As another point I can't see any code that adds the JComponent you created (e.g. the buttons, the text fields,...) to the two frames of the respective classes or that displays the two frames; if it isn't included in your code be sure to add these pieces of code).
Finally, if you need a code that checks for changes in the value of Updated, here's the simplest (but not the only) technique you can use, creating a thread (see the Oracle documentation to know what are threads and how to use them):
int refreshTime = 1000; // Refresh time in milliseconds
boolean running = true; // Set it to false if you want to stop the thread
Runnable r = new Runnable({
#Override
public void run() {
while(running) {
Thread.sleep(refreshTime);
// Put here your code to update your frames or your variables
}
});

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);

Create dynamic form from vector or array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
First of all, I'm new in java.
I would like to generate forms dynamically based on Arrays, I was able to generate the fields, but I do not know how to read them, I couldn't find something like text field index or something.
So basically i'm asking how to read values from a TextField component that has no reference.
JTextField myText = new JTextField() vs new JTextField(), added to a panel
Below is a simple code example, any idea is welcomed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame{
private JPanel p1 = new JPanel();
private JButton btn = new JButton("Read Data");
public Test(){
super("Dynamic Form");
setLayout(new GridLayout(4,2));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Declare the Array with fields
String[] fList = new String[3];
fList[0] = "id";
fList[1] = "firstName";
fList[2] = "lastName";
//Iterate fields array and add elements
for(int i = 0; i<fList.length; i++){
add(new JLabel(fList[i]));
add(new JTextField("field: "+fList[i]));
}
add(p1);
add(btn);
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev){
String id = "id field value is: "; // + some code to get actual text field value
String firstName = "firstName field value is: "; // + some code to get actual text field value
String lastName = "lastName field value is: "; // + some code to get actual text field value
System.out.println(id+ " " + firstName + " " + lastName);
}
}
);
pack();
setLocationRelativeTo(null);
setResizable(true);
setVisible(true);
}
public static void main(String [] args){
new Test();
}
}
You need to store references to those text fields somewhere.
List<JTextField> fields = new ArrayList<>();
...
for(int i = 0; i<fList.length; i++){
JTextField field= new JTextField("field: "+fList[i]);
add(new JLabel(fList[i]));
add(field);
fields.add(field);
}
Now you can access them from your fields list:
public void actionPerformed(ActionEvent ev){
String id = "id field value is: " + fields.get(0).getText();
String firstName = "firstName field value is: " + fields.get(1).getText();
String lastName = "lastName field value is: " + fields.get(2).getText();
System.out.println(id+ " " + firstName + " " + lastName);
}

Advance to next card object with different elements while using java's cardlayout

I am very new to this site and a novice programmer so I'm hoping someone here can help me with the problem I'm facing. I am making a simple program that uses a card layout to select/enter several user-specific options that will be stored in string variables and then after the last question, used to give a unique answer. Right now the program advances slide's successfully and displays the proper question, however it does not clear the JRadioButton from the first card and keeps using this radio button instead of the desired component for the duration of the program. For example, The second and third card should have JTextField's while the 4th card should have a JComboBox. I have two main class files, one that is the actual frame and the other that is displayed below which does the work behind the scenes. For future reference, I plan to modify this into an applet once it is working properly so any advice on that would be great. Any help will be greatly appreciated, thanks.
I believe the problem may stem from the creation of multiple card objects here, the ScreenPanel objects each take the same parameters but depending on the different card, a different Component needs to be produced.
// set up questions
String question1 = "Sex: ";
String[] responses1 = {"Female", "Male"};
ask[0] = new ScreenPanel(question1, responses1);
String question2 = "Height in inches: ";
String[] responses2 = new String[1];
ask[1] = new ScreenPanel(question2, responses2);
String question3 = "Weight in pounds: ";
String[] responses3 = new String[1];
ask[2] = new ScreenPanel(question3, responses3);
String question4 = "Event: ";
String[] responses4 = {"Shot Put", "Discus Throw", "Long Jump", "Triple Jump", "High Jump", "Pole Vault", "4 x 800 Relay", "100 Meter Hurdles", "100 Meter Dash", "4 x 200 Relay",
"1600 Meter Run", "4 x 100 Relay", "400 Meter Dash", "300 Meter Hurdles", "800 Meter Run", "200 Meter Dash", "3200 Meter Run", "4 x 400 Relay"};
ask[3] = new ScreenPanel(question4, responses4);
String question5 = "Distance(inches) or Time(seconds)";
ask[4] = new ScreenPanel(question5, new String[1]);
ask[4].setFinalQuestion(true);
addListeners();
}
The Screen Panel class here creates each card, could be a problem with the conditionals but not sure.
class ScreenPanel extends JPanel{
JLabel question;
JRadioButton[] response1;
JTextField response2;
JTextField response3;
JComboBox response4;
JTextField response5;
JButton nextButton = new JButton("Next");
JButton finalButton = new JButton("Finish");
String textResponse1, textResponse2, textResponse3, textResponse4, textResponse5;
ScreenPanel(String ques, String[] resp){
super();
setSize(320, 260);
question = new JLabel(ques);
JPanel sub1 = new JPanel();
JPanel sub2 = new JPanel();
sub1.add(question);
if (TrackAndField.currentScreen == 0){
response1 = new JRadioButton[resp.length];
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < resp.length; i++){
response1[i] = new JRadioButton(resp[i], false);
group.add(response1[i]);
sub2.add(response1[i]);
}
// textResponse1 = group.getSelection().toString();
}
if (TrackAndField.currentScreen == 1){
sub2.remove(response1[0]);
sub2.remove(response1[1]);
response2 = new JTextField(4);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse2 = response2.getText();
}
};
sub2.add(response2);
}
if (TrackAndField.currentScreen == 2){
sub2.remove(response2);
response3 = new JTextField(10);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse3 = response3.getText();
}
};
sub2.add(response3);
}
if (TrackAndField.currentScreen == 3){
sub2.remove(response3);
response4 = new JComboBox(resp);
sub2.add(response4);
textResponse4 = response4.getSelectedItem().toString();
}
Solved by adding an extra string parameter as an ID for the component and used that for the conditionals instead of currentScreen

Throwing a value to the other class

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.

Categories

Resources