Clearing JTextfields to write multiple data to txt file - java

excuse the probably simple question (and the terrible layout methods). The code I have successfully writes inputted data to a txt file and on clicking "submit" closes the input window, leaving the "menu" open, with options to add a user (this code) or search properties (unrelated). I can enter one set of details to the txt file with no problem, but when reopening the AddUser window, no matter what is typed in to the boxes the same data is inputted into the file as the previous time, unless the program is closed. I think it has something to do with clearing some variable before reopening the window (as tried towards the bottom) however i haven't had any luck.. How do I go about it? Thanks
AddUser.java
package assignment;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.lang.*;
public class AddUser extends JFrame {
//Declare the array values
private String[] Name;
private String[] Username;
private String[] Password;
private String[] StaffID;
public String inputStaff;
public String inputUser;
public String inputPass;
public String inputID;
static public String inputData;
//Declare Text Fields
public JTextField Field1;
public JTextField Field2;
public JTextField Field3;
public JTextField Field4;
public JTextField Field5;
//Declare Labels
private JLabel Label;
private JLabel Label1;
private JLabel Label2;
private JLabel Label3;
private JLabel Label4;
private JLabel Label5;
private JLabel Space1;
private JLabel Space2;
public AddUser() {
super("Add New Agent"); //Window Title
setLayout(new FlowLayout(FlowLayout.LEFT)); //Set Layout Type as FlowLayout
Label = new JLabel("Enter the Member of Staff's Details");
Label1 = new JLabel("Staff Name"); //Label Values
Label2 = new JLabel("Username");
Label3 = new JLabel("Password");
Label4 = new JLabel("Confirm Password");
Label5 = new JLabel("Staff ID");
Space1 = new JLabel(" ");
Space2 = new JLabel(" ");
Field1 = new JTextField (10); //Create the Text Fields and Option Blocks & Arguments
Field2 = new JTextField (10);
Field3 = new JTextField (10);
Field4 = new JTextField (10);
Field5 = new JTextField (4);
//Add the labels, textfields and option blocks to the JFrame
add (Label); add(Space1); add (Label1); add (Field1); add (Label2); add (Field2); add (Label3); add (Field3); add (Label4);
add (Field4); add (Label5); add (Field5); add (Space2);
JButton button1 = new JButton("Submit"); //Add "Search" button to JFrame
add (button1);
onClick handler = new onClick();
button1.addActionListener(handler);
}
private class onClick implements ActionListener{
public void actionPerformed(ActionEvent event){
//Action to be performed
//Attempt to clear the fields
inputStaff = ("");
inputUser = ("");
inputPass = ("");
inputID = ("");
inputStaff = Field1.getText();
inputUser = Field2.getText();
inputPass = Field3.getText();
inputID = Field5.getText();
inputData = inputStaff + " " + inputUser + " " + inputPass + " " + inputID;
WriteFile Write = new WriteFile(); //Create instance of write-to-file
setVisible(false);
//Close the window on clicking submit
}
}
}
The write to file code (WriteFile.java) is as follows;
package assignment;
import java.io.*;
public class WriteFile{
static String data = AddUser.inputData;
BufferedWriter out;
public WriteFile(){
try {
out = new BufferedWriter(new FileWriter("AddUser.txt", true));
out.write(data);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}

This way to achieve that lacks in a few manners, please consider the following:
public static void WriteFile(String data){
try {
out = new BufferedWriter(new FileWriter("AddUser.txt", true));
out.write(data);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
And call it like that:
WriteFile.WriteFile(inputData);
I would also change the name of the method, but I tried to keep it as close as possible to the original code.
Don't access fields of a class in this way SomeClass.someField, and try to avoid static members when they are not needed.

The line
static String data = AddUser.inputData;
is only run once, when the class is loaded. That is the case with all static variables. (You appear to be thinking along the lines of "dataflow programming" or spreadsheets, but Java doesn't work like that. Or you might be thinking that String objects are updateable, but they're not - they're immutable.)
This is a terrible way to implement data passing between classes, and as you can see, it doesn't work. It wouldn't even work once if for some reason that class happened to be loaded earlier than it was.

Related

Refer to an individual JTextField when they're in different tabs

I have three JTextFields, when the buy button is pressed the associated listener should retrieve the text from the text fields and use it to update the table.
The issue is that when I press the buy button it tries to use the data in the JTextFields in David's tab as opposed to the one I'm currently on. If I made another tab named "Jack" it would then try to be using jacks. The code to create the text boxes is as follows:
JLabel label2 = new JLabel("Name Of Share:");
tabPanel.add(label2);
textFieldName = new JTextField("", 15);
textFieldName.setColumns(10);
textFieldName.setToolTipText("Enter Number of shares here");
tabPanel.add(textFieldName);
The listener for the buy button:
int quantity = 0;
if (e.getActionCommand().equals("Buy")) {
String name = view.getTextFieldName().getText();
String ticker = view.getTextFieldTicker().getText().toUpperCase();
try{
quantity = Integer.parseInt(view.getTextFieldNumber().getText());
}catch(NumberFormatException er){
}
view.buy(ticker, name, quantity);
}
Everything works fine if I only have one tab but once I introduce more that's when the issues start.
Can anyone suggest a way to fix this so I can get data from the text boxes of only the tab I am on?
I should have mentioned view is of type MainGUI a Class I have created, which is used for building the GUI which has the fields:
public class MainGUI extends JFrame implements Observer {
private JTabbedPane tabbedPane;
private JTable table;
private JTextField textFieldTicker;
private JTextField textFieldName;
private JTextField textFieldNumber;
private DefaultTableModel model;
private PortfolioManager pm;
private JLabel tValue;
to create a Tab the code used is:
JPanel topPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
JSplitPane splitPanelbtm = new JSplitPane(JSplitPane.VERTICAL_SPLIT, labelPanel, buttonPanel);
JSplitPane splitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, splitPanelbtm){
private final int location = 500;
{setDividerLocation(location);}
#Override
public int getDividerLocation(){
return location;
}
#Override
public int getLastDividerLocation(){
return location;
}
};
splitPanel.setEnabled( false );
splitPanel.setDividerSize(0);
splitPanelbtm.setEnabled( false );
splitPanelbtm.setDividerSize(0);
splitPanelbtm.setBorder(null);
splitPanel.setBorder(null);
tabbedPane.add(tabName, splitPanel);
tabbedPane.setName(tabName);
this.add(tabbedPane);
this.setVisible(true);
createLabelsButtons(topPanel);
createTable(topPanel);
tValue = new JLabel("Total Value for " + tabbedPane.getName() + " is: $ ");
labelPanel.add(tValue);
createTabButtons(buttonPanel);

how to open a second jframe from a current one?

my current program takes in text from some JTextFields and adds it to a file to keep track of medications. What i want to do, is add another button to the bottom of the program that will open a second jframe to display the medications that are already documented, but all attempts have been brutally unsuccessful. Below is the code that i am currently working with.
Much Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
#SuppressWarnings({ "serial" })
public class MedGUITest extends JFrame {
private JLabel medName;
private JLabel medTime;
private JLabel medDose;
private JLabel finished;
private JTextField textFieldMed;
private JTextField textFieldTime;
private JTextField textFieldDose;
private JButton submitButton;
private JButton meds;
public MedGUITest(){
setLayout(new FlowLayout());
medName = new JLabel("Type Medication Here:");
add(medName);
textFieldMed = new JTextField("",15);
add(textFieldMed);
medDose = new JLabel("Type Medication Dose:");
add(medDose);
textFieldDose = new JTextField("",15);
add(textFieldDose);
medTime = new JLabel("Type Medication Time:");
add(medTime);
textFieldTime = new JTextField("",15);
add(textFieldTime);
submitButton = new JButton("Click Here to Add");
event e = new event();
submitButton.addActionListener(e);
add(submitButton);
meds = new JButton("Click Here to see meds");
event2 r = new event2();
meds.addActionListener(r);
add(meds);
finished = new JLabel("");
add(finished);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
String medName = textFieldMed.getText();
String medDose = textFieldDose.getText();
String medTime = textFieldTime.getText();
File med = new File("med.txt");
try(PrintWriter out= new PrintWriter(new FileWriter(med,true))) {
out.println("Medication: " + medName + " " +"Dosage: "+ medDose + " Mg"+ " " +"Time of day: "+ medTime);
finished.setText("Your Med has been added");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class event2 implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String args[]) throws IOException{
int winWidth = 300;
int winLength = 300;
MedGUITest gui = new MedGUITest();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(winWidth, winLength);
gui.setVisible(true);
gui.setTitle("Standard GUI");
}
}
You would probably want to use a JDialog instead of another JFrame. You just set it up the same way you set up any other JFrame or JDialog. You create the frame/dialog, add components and then call pack() then setvisible(true). You just want to make sure that you don't set JFrame.setDefaultCloseOperation() to close when the close your second JFrame.
I find it easier to set up my classes to sub-class JPanel instead of JFrame so then it is easier to reuse it in other places.

Make JOptionPane message dialog box dissappear after rendering

I am building a simple JFrame GUI requiring user input. If the user clicks the submit button, it checks for input then either renders a JOptionPane message telling the user to completely fill out the form, or it tells the user that the form submitted and closes the program. The problme is that if the user left blank fields, the message dialog box renders and only adds to the loop count if you try to close it and does not allow the user to return to the JFrame to apply input to the form.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.util.Scanner.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author joel.ramsey
*/
public class JRStarPhase5 extends JFrame{
public static void main (String [] args) throws IOException {
JFrame window = new JRStarPhase5();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}//end main method
private boolean validationError;
private final JTextField fNameInput;
private final JTextField miInput;
private final JTextField lNameInput;
private final JTextField productChoiceInput;
private final JTextField licenseQuantityInput;
private final JTextField streetAddressInput;
private final JTextField cityInput;
private final JTextField stateInput;
private final JTextField zipInput;
private final JTextField phoneInput;
//constructor for JFrame
public JRStarPhase5(){
setTitle("JRStar Star Gaze Order Processing");
setSize (800,800);
Container pane = getContentPane();
GridLayout grid = new GridLayout(0,2);
pane.setLayout(grid);
JLabel fNameLabel = new JLabel ("First name:");
JLabel mi = new JLabel ("Middle initial:");
JLabel lNameLabel = new JLabel ("Last name:");
JLabel productChoice = new JLabel ("Star Gaze version:");
JLabel licenseQuantity = new JLabel ("License quantity:");
JLabel streetAddress = new JLabel ("Street address:");
JLabel city = new JLabel ("City:");
JLabel state = new JLabel ("State abbrev:");
JLabel zip = new JLabel ("Zip code:");
JLabel phone = new JLabel ("Phone Number:");
this.fNameInput = new JTextField(15);
this.miInput = new JTextField (1);
this.lNameInput = new JTextField (15);
this.productChoiceInput = new JTextField (1);
this.licenseQuantityInput = new JTextField (2);
this.streetAddressInput = new JTextField (20);
this.cityInput = new JTextField (20);
this.stateInput = new JTextField (2);
this.zipInput = new JTextField (5);
this.phoneInput = new JTextField (10);
//add as last buttons
JButton submit = new JButton("Submit");
SubmitButtonHandler sbh = new SubmitButtonHandler();
submit.addActionListener(sbh);
JButton clear = new JButton("Clear");
ClearButtonHandler cbh = new ClearButtonHandler();
clear.addActionListener(cbh);
pane.add(fNameLabel);
pane.add(fNameInput);
pane.add(mi);
pane.add(miInput);
pane.add(lNameLabel);
pane.add(lNameInput);
pane.add(productChoice);
pane.add(productChoiceInput);
pane.add(licenseQuantity);
pane.add(licenseQuantityInput);
pane.add(streetAddress);
pane.add(streetAddressInput);
pane.add(city);
pane.add(cityInput);
pane.add(state);
pane.add(stateInput);
pane.add(zip);
pane.add(zipInput);
pane.add(phone);
pane.add(phoneInput);
//add last
pane.add(submit);
pane.add(clear);
}//end constructor
private class SubmitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
validationError = (fNameInput.getText().equals("")||
miInput.getText().equals("")||
lNameInput.getText().equals("")||
streetAddressInput.getText().equals("")||
cityInput.getText().equals("")||
stateInput.getText().equals("")||
zipInput.getText().equals("")||
phoneInput.getText().equals(""));
for (int n=1; n<3; n++){
if (validationError){
if (n == 3){
System.exit(0);
}
JOptionPane.showMessageDialog(null,"Please complete each field within the order form.");
}
else break;
}
if (validationError = false)
JOptionPane.showMessageDialog(null,"Your order has been submitted!");
System.exit(0);
}
}//end submit
private class ClearButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
fNameInput.setText("");
miInput.setText("");
lNameInput.setText("");
productChoiceInput.setText("");
licenseQuantityInput.setText("");
streetAddressInput.setText("");
cityInput.setText("");
stateInput.setText("");
zipInput.setText("");
phoneInput.setText("");
}
}//end clear
}//end main class
I honestly don't know what else you expected (no offense).
Swing is a event driven environment. An event occurs, you react to it...
The loop will execute within the context of the EDT to start with, meaning that there is no way a user could actually close the dialog, correct the error and try to re-submit.
Even if it did, the loop does not allow for any opportunity for the validationError variable to be re-evaluated, meaning it will always be what it was originally set to earlier in the method (lets assume true for now)...
for (int n = 1; n < 3; n++) {
if (validationError) {
if (n == 3) {
System.exit(0);
}
JOptionPane.showMessageDialog(null, "Please complete each field within the order form.");
} else {
break;
}
}
if (validationError = false) {
JOptionPane.showMessageDialog(null, "Your order has been submitted!");
}
System.exit(0);
So basically you have a death trap, there is simply no way to escape...
Let's take another approach. Rather than using a hard-loop, like for or while, we can create a soft loop, whereby, each time the method is executed and the form is invalid, we update a counter, until that counter runs out...
// How many times retries has the user used...
private int retries = 0;
/*...*/
public void actionPerformed(ActionEvent e) {
validationError = (fNameInput.getText().equals("")
|| miInput.getText().equals("")
|| lNameInput.getText().equals("")
|| streetAddressInput.getText().equals("")
|| cityInput.getText().equals("")
|| stateInput.getText().equals("")
|| zipInput.getText().equals("")
|| phoneInput.getText().equals(""));
if (validationError) {
retries++;
if (retries < 3) {
JOptionPane.showMessageDialog(this, "Please complete each field within the order form.");
} else {
JOptionPane.showMessageDialog(this, "You've used up all your tries...");
System.exit(0);
}
} else {
JOptionPane.showMessageDialog(this, "Your order has been submitted!");
System.exit(0);
}
}
You may also like to have a read of Validating Input from the How to use the focus subsystem tutorial...

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

How do I store information from the textFields?

Right now, I'm just testing the to make sure the button works...but this is my code for an applet that expands a binomial using Pascal's triangle! I have the equations for the actually figuring out part, I just need to know how to store the information from the JTextFields! Thanks!
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.Action;
public class BinomialExpander extends JApplet implements ActionListener
{
JLabel welcome;
JLabel directions;
JLabel example;
JLabel instructions;
JLabel startOfBinomial;
JLabel plusSign;
JLabel forExponent;
JLabel endOfBinomial;
JTextField txtFirst;
JTextField firstVar;
JTextField txtSecond;
JTextField secondVar;
JTextField exp;
JLabel lblExpanded;
JLabel outputExpanded;
double degreesFahrenheit;
FlowLayout layout;
Timer timer;
Button compute;
private int[] pascal1 = {1,1};
private int[] pascal2 = {1,2,1};
private int[] pascal3 = {1,3,3,1};
private int[] pascal4 = {1,4,6,4,1};
private int[] pascal5 = {1,5,10,10,5,1};
private int[] pascal6 = {1,6,15,20,15,6,1};
private int[] pascal7 = {1,7,21,35,35,21,7,1};
private int[] pascal8 = {1,8,28,56,70,56,28,8,1};
private int[] pascal9 = {1,9,36,84,126,84,36,9,1};
private int[] pascal10 = {1,10,45,120,210,120,45,10,1};
public void init()
{
Container c = getContentPane();
c.setBackground(Color.cyan);
layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
c.setLayout(layout);
setSize(500,175);
welcome = new JLabel("Welcome to the Binomial Expander Applet!");
directions = new JLabel("Enter binomial in the form: '(number)(variable) + (number)(variable)^exponent'.");
example = new JLabel("Example: (4a + 2)^2.");
// instantiate JLabel object for Degrees Fahrenheit
instructions = new JLabel("Enter the first number of your binomial(if there is a variable, add it into the second box):");
// instantiate JTextField object for the degrees fahrenheit
startOfBinomial = new JLabel(" (");
txtFirst = new JTextField(4);
// instantiate JLabel object for Degrees Celesius
firstVar = new JTextField(4);
plusSign = new JLabel(" + ");
txtSecond = new JTextField(4);
secondVar = new JTextField(4);
endOfBinomial = new JLabel(")");
forExponent = new JLabel("^");
forExponent.setFont(new Font("Times New Roman", Font.BOLD, 9));
exp = new JTextField(2);
compute = new Button("Compute!");
compute.addActionListener(this);
lblExpanded = new JLabel("Your expanded binomial is: ");
// JLabel to display the equivalent degrees Celsius
outputExpanded = new JLabel("");
c.add(welcome);
c.add(directions);
c.add(example);
c.add(instructions);
c.add(startOfBinomial);
//CALL the addActionListener() method on the JTextField object
// for the degrees Fahrenheit
txtFirst.addActionListener(this);
// Add the textbox the celsius label and output label
c.add(txtFirst);
c.add(firstVar);
c.add(plusSign);
c.add(txtSecond);
c.add(secondVar);
c.add(endOfBinomial);
c.add(forExponent);
c.add(exp);
c.add(compute);
c.add(lblExpanded);
c.add(outputExpanded);
// timer = new Timer(1, this);
// timer.start();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
}
public String expand()
{
String x = "callingComputing";
return x;
}
}
yourTextField.getText() returns a String you can use as you would any other String, store it in an array, teach it to sing, fly and enjoy life.
Conversely, you can use yourTextField.setText() to display stuff in your JLabel, textfield etc.
JTextField extends JTextComponent, which has API to deal text manipualtion.
As suggested by other answers use setText to replace the current text with new text.
Also read the official tutorial to understand How to Use Text Fields
JTextField txtName = new JTextField();
JButton btn = new JButton();
in the action performed method add this
String name = txtname.getText();
this statement returns the text that is entered in the text field the second before you click the button
You create a class where you'll store the data, and create an object of that in the Frame class, i.e. the class that'll provide the GUI to the data class, then in the action listener of the submit button of the frame assign the getText() returned string to the object's field
for eg: you want to take input name and age from the text field,
create a Person class
public class Person{
public String name;
public int age;
}
now create a GUI class
public PersonFrame extends JFrame{
public person;
public PersonFrame(){
person = new Person();
JTextField txtName = new JTextField();
JButton btn = new JButton();
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
person.name = txtName.getText();
person.age = Integer.parseInt(txtAge.getText()); //as the textfield returns a String always
}
});
}
}
and avoid using
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
If you have 100 button it'll be foolish to write nested if-else statements to check which button generated the event!!
remember that swing is designed for providing the user interface and you need an object of a class for storing the data!
for java tutorial visit here

Categories

Resources