Java GUI Variables Problems - java

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)

Related

Java - Jframe not displaying Buttons Labels or textfields

im new to java but when I try to create a new frame all I get is a new window open with a white background on and none of the buttons or text boxes or labels get added. I don't know what im doing wrong?
private static void MainGui(){
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle(name+ "'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MainInterfaces Class
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
Your code doesn't compile because you have a lot of errors (you have no main method, private static void MainGui(){ makes no sense etc.). Try this code instead which compiles and opens the GUI fine for me, showing everything as you want to (the buttons, the labels, etc.):
1) Class MainGui.java
class MainGui{
public static void main(String[] args) {
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle("'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(MainGui.EXIT_ON_CLOSE);
}
}
2) Class MainInterfaces.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
I fixed it with one line of code. Just switch the "setVisible(true)" method to being inside the MainInterface class. However, make sure you put it as the last line of code inside the constructor, or it won't work. Basically, what was happening is that while the frame itself was being set to be true, the components were being added afterwards and were consequently not being shown. Putting "setVisible(true)" last makes sure all the components are added when you display the frame.
As a side note, you can add all methods you typed in the MainGUI class inside of MainInterface.
Here's MainGUI:
public class MainGUI
{
public static void main(String[] args)
{
new MainInterfaces();
}
}
Here's what MainInterfaces looks likes:
public class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces()
{
setTitle("(Name)'s Inbox");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl); add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}

Fetch TextField value by pressing Jbutton

Here is the problem:
I want an interactive GUI that has a TextField and a JButton. Users enter their pincode in TextField, press the JButton and the value fetches from main class to use as an argument in a function.
This is my JFrame with TextField and Button code:
public class JTextFieldDemo extends JFrame {
//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
ButtonHandler handler = null;
String pin;
//Constructor
public JTextFieldDemo() {
super("Smart Token Utility");
Container container = getContentPane();
container.setLayout(new FlowLayout());
jtfText1 = new JTextField(10);
jtfUneditableText = new JTextField("Please Enter Your PIN Code", 20);
jtfUneditableText.setEditable(false);
container.add(jtfText1);
container.add(jtfUneditableText);
handler = new ButtonHandler();
JButton button = new JButton("Enter");
button.setSize(3,5);
button.addActionListener(handler);
container.add(button);
setSize(325, 100);
setLocationRelativeTo(null);
setVisible(true);
jtfText1.addActionListener(handler);
}
//Inner Class ButtonHandler
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
pin = jtfText1.getText();
}
}
and This is my main class code:
public static void main(String args[]) {
JTextFieldDemo test = new JTextFieldDemo();
String pincode = test.pin;
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyStore.load(null, pincode);
}
I have two problems:
1) When I run the main class, the Jframe appears and before I can type anything in TextField it disappears.
2) The pincode in the main class is always null even if I hardcoded it in ButtonHandler class.
As your main method get the pin code after creation of the JFrame, it will have the default value-null. So Getting the pin code(KeyStore.load(null, pincode)) method should be in ButtonHandler#actionPerformed().
But in your case you can use JOptionPane#showInputDialog(java.lang.Object, java.lang.Object) to get the input.

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...

Linking single listener to multiple buttons

Hello I am having an issue when linking a single listener to multiple buttons. I'm trying to use inner classes but it seems I'm getting it wrong somewhere. Can someone point me to the right direction?
If it helps the auto-correct thingy ( :D ) points to line 59 saying:
"createChampButton cannot be resolved to a variable"
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JApplet{
public void init(){
Container guiContainer = getContentPane();
LayoutManager layout = new FlowLayout();
guiContainer.setLayout(layout);
//Create Championship Button
final JButton createChampButton = new JButton("Create Championship");
guiContainer.add(createChampButton);
//Create Club Button
final JButton createClubButton = new JButton ("Create Club");
guiContainer.add(createClubButton);
//Create Athlete Button
final JButton createAthleteButton = new JButton ("Create Athlete");
guiContainer.add(createAthleteButton);
//Print Athletes Button
final JButton printAthletesButton = new JButton ("Print all Athletes");
guiContainer.add(printAthletesButton);
//The quiet Listener
ButtonListener aListener = new ButtonListener();
printAthletesButton.addActionListener(aListener);
createAthleteButton.addActionListener(aListener);
createClubButton.addActionListener(aListener);
createChampButton.addActionListener(aListener);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
//if (button.equals(printAthletesButton)){
//JOptionPane.showMessageDialog(null, "Athlete name is: " +anAthlete.GetAthleteName());
// JOptionPane.showMessageDialog(null, "Athlete age is: " + anAthlete.GetAge());
//}
if(button.equals(createChampButton)){
Championship aChampionship = new Championship("","");
aChampionship.champName = JOptionPane.showInputDialog("Enter Championship Name: ");
aChampionship.duration = JOptionPane.showInputDialog("Enter Championship Duration: ");
}
}
}
}
thanks in advance,
Chris
createChampButton is a local variable in init()
To access it elsewhere, you need to change it to a field in the class.
createChampButton is not defined in your other method, so the scope doesn't make possible that you access that. I see three options how you can work around that:
1) You use component.getActionCommand() instead - you can compare it with the text that your JButton holds (something like if( evt.getSource().getActionCommand().equals("Create Championship")
2) You can define your ActionListener within your init method:
public void init(){
Container guiContainer = getContentPane();
LayoutManager layout = new FlowLayout();
guiContainer.setLayout(layout);
//Create Championship Button
final JButton createChampButton = new JButton("Create Championship");
guiContainer.add(createChampButton);
//Create Club Button
final JButton createClubButton = new JButton ("Create Club");
guiContainer.add(createClubButton);
//Create Athlete Button
final JButton createAthleteButton = new JButton ("Create Athlete");
guiContainer.add(createAthleteButton);
//Print Athletes Button
final JButton printAthletesButton = new JButton ("Print all Athletes");
guiContainer.add(printAthletesButton);
//The quiet Listener
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
//if (button.equals(printAthletesButton)){
//JOptionPane.showMessageDialog(null, "Athlete name is: " +anAthlete.GetAthleteName());
// JOptionPane.showMessageDialog(null, "Athlete age is: " + anAthlete.GetAge());
//}
if(button.equals(createChampButton)){
Championship aChampionship = new Championship("","");
aChampionship.champName = JOptionPane.showInputDialog("Enter Championship Name: ");
aChampionship.duration = JOptionPane.showInputDialog("Enter Championship Duration: ");
}
}
};
printAthletesButton.addActionListener(aListener);
createAthleteButton.addActionListener(aListener);
createClubButton.addActionListener(aListener);
createChampButton.addActionListener(aListener);
}
}
3) You define your JComponents as instance variable - declaring them outside your init() method (but assigning them inside, still)
Regards,
Danyel

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