JTextField? I just started learning Java about a month ago
I have several JTextField in a JFrame. I want to be able to enter numbers in these JTextFields and then with a press of a button have the program return some calculations.
I declared integers in the begining of the program and then converted the the data that is enetered into JTextField to integers. It didn't work.
Can you explain theoretically how I can get from a point of entering numbers into JTextField to using those numbers in some calculations
[474 byte] By [
idimaia] at [2007-9-28 13:52:09]

idimai:
From JTextField, you will get a String value, returned by using getText() method. Then, in order to parse them to type int, you use parseInteger() method of class Integer.
For example,
String val1Str = txtField1.getText();
int val1 = Integer.parseInteger(val1Str);
String val2Str = txtField2.getText();
int val2 = Integer.parseInteger(val2Str);
int total = val1 + val2;
// Display in another JTextField
Integer total = new Integer(total);
txtFieldTotal.setText(total.toString());
Hope this help. All the best!
Thank you, actually that's what I though. I'm getting some errors though
Can you look at the code and tell me what's wrong. thanks again.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class StudentTracker extends JFrame { // create a class of type JFrame
JTextField SsnField, FirstNameField, LastNameField, Test1Field, Test2Field,
Test3Field, HomeworkField, FinalTestField, prompt;
int finalGrade, test1Grade, test2Grade, test3Grade, finaltestGrade,homeworkGrade ;
JTextArea outputTextArea = new JTextArea();
public StudentTracker(String title) // constructor method - initializes object
{
super (title); // set window title
Container c;
addWindowListener(new WindowAdapter() // handle window being closed by clicking on x box
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); // terminate normally
}
});
c = getContentPane();
c.setLayout(new GridLayout(10,2)); // set window up as a 3x3 grid
c.add(new JLabel("Enter Students SSN"));
SsnField = new JTextField ("");
SsnField.selectAll (); // select text for overtyping
c.add(SsnField);
c.add(new JLabel("First Name"));
FirstNameField = new JTextField ("");
FirstNameField.selectAll (); // select text for overtyping
c.add(FirstNameField);
c.add(new JLabel("Last Name"));
LastNameField = new JTextField ("");
LastNameField.selectAll (); // select text for overtyping
c.add(LastNameField);
c.add(new JLabel("Test #1 Score"));
Test1Field = new JTextField ("");
Test1Field.selectAll ();
c.add(Test1Field);
c.add(new JLabel("Test #2 Score"));
Test2Field = new JTextField ("");
Test2Field.selectAll ();
c.add(Test2Field);
c.add(new JLabel("Test #3 Score"));
Test3Field = new JTextField ("");
Test3Field.selectAll ();
c.add(Test3Field);
c.add(new JLabel("Homeworkd Score"));
HomeworkField = new JTextField ("");
HomeworkField.selectAll ();
c.add(HomeworkField);
c.add(new JLabel("Final Test Score"));
FinalTestField = new JTextField ("");
FinalTestField.selectAll ();
c.add(FinalTestField);
JButton calculateButton = new JButton ("Calculate Grade");
calculateButton.addActionListener (new MyActionListener());
c.add (calculateButton);
JButton nextButton = new JButton ("Next Student");
nextButton.addActionListener (new MyActionListener()); // prepare button for event handling
c.add (nextButton);
JButton exitButton = new JButton ("Exit");
exitButton.addActionListener (new MyActionListener());
c.add (exitButton);
JButton displayButton = new JButton ("Display");
displayButton.addActionListener (new MyActionListener());
c.add (displayButton);
test1Grade = Integer.parseInt(Test1Field);
test2Grade = Integer.parseInt(Test2Field);
test3Grade = Integer.parseInt(Test3Field);
homeworkGrade = Integer.parseInt(HomeworkField);
finaltestGrade = Integer.parseInt(FinalTestField);
finalGrade = (test1Grade + test2Grade + test3Grade + homeworkGrade)/4;
pack(); // shrink window to miniminum size needed
setVisible(true); // make window visible
}
public static void main(String args[]) // program entry point
{
System.out.println("...Initializing Student Tracker...");
StudentTracker mainWindow = new StudentTracker("Student Tracker v1.0"); // create new object of class SimpleGreeting
}
class MyActionListener implements ActionListener { //inner class to handle button event
public void actionPerformed(ActionEvent evt) {
outputTextArea.setText();
outputTextArea.append( "" );
// if (evt.getActionCommand ().equals("Display")) // determine //origin of event
//JOptionPane.showMessageDialog ( //null,outputTextArea ,"Display",JOptionPane.INFORMATION_MESSAGE );
//JOptionPane.showMessageDialog (null,
// SsnField.getText() + FirstNameField.getText() + LastNameField.getText() + Test1Field.getText() + Test2Field.getText()
//+ Test3Field.getText() + HomeworkField.getText() + FinalTestField.getText() , "You entered ...", JOptionPane.INFORMATION_MESSAGE);
if (evt.getActionCommand ().equals("Calculate Grade"))
JOptionPane.showMessageDialog ( null,
+ finalGrade ,"Final Grade", JOptionPane.INFORMATION_MESSAGE);
else if (evt.getActionCommand ().equals("Exit"))
System.exit(0); // terminate program normally
}
}
}
sorry it's a bit screwed up in the end, the if statement, I was trying to block out the first dialogue box and didn't block it out completely
You cannot directly parse the Jtext field .Just replace all your parse statements as follows :Replace Integer.parseInt(Test1Field);withInteger.parseInt(Test1Field.getText());
Thanks, that worked, however, even though the program compiled successfully when i run it i get the following error :
Exception in thread "main" java.lang.NumberFormatException:
at java.lang.Integer.parseInt(Integer.java:435)
at java.lang.Integer.parseInt(Integer.java:463)
at StudentTracker.<init>(StudentTracker.java:99)
at StudentTracker.main(StudentTracker.java:116)
what's that all about
move you parsing and calculation stuff in actionPerformed method of MyActionListener
following code you will need to move :
test1Grade = Integer.parseInt(Test1Field.getText());
test2Grade = Integer.parseInt(Test2Field.getText());
test3Grade = Integer.parseInt(Test3Field.getText());
homeworkGrade = Integer.parseInt(HomeworkField.getText());
finaltestGrade = Integer.parseInt(FinalTestField.getText());
finalGrade = (test1Grade + test2Grade + test3Grade + homeworkGrade)/4;
How can I make a JTable box appear in the middle of the screen when the program starts running.Currently it appears in the top left corner.
I would also like to create arrays so that when the information is entered and you press " Next Student" the textboxes clear and I can continue entering the information until I click Display, and that's when I want it to display all the information for multiple students.any Ideas?
Following change should place ur window in center
public static void main(String args[]) // program entry point
{
System.out.println("...Initializing Student Tracker...");
StudentTracker mainWindow = new StudentTracker("Student Tracker v1.0"); // create new object of class SimpleGreeting
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dm = tk.getScreenSize();
mainWindow.setSize(250,300);
mainWindow.setLocation( dm.width /2-150, dm.height/2 -150);
}
I am not very sure how you are going to do the display thing. You dont want to store the data ? If you dont want to store the data then you can write your own implementation for storing it in memory and if you want to store it then use some file objects for storing.
Let me know if you have any more queries
Thanx for your tips, they have been very helpful.
I have several more questions
1) I would like to convert strings into doubles instead of Integers and when I do that I get a bunch of error messages.
Such as:
C:\Program Files\JCreator LE\MyProjects\StudentRecords\GUI\JavaProject\StudentTracker\StudentTracker.java:141: possible loss of precision
found: double
required: int
test1Grade = Double.parseDouble(Test1Field.getText());
2) I would like to be able to print the text that is entered into the JTextField later on with a press of a button. I have it set up already and the code copiles without errors, however, when I run the program instead of working I get the following error message in the comand prompt:
41)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1
50)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstr
ctButton.java:1504)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonMode
.java:378)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:25
)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButton
istener.java:216)
at java.awt.Component.processMouseEvent(Component.java:3715)
at java.awt.Component.processEvent(Component.java:3544)
at java.awt.Container.processEvent(Container.java:1164)
at java.awt.Component.dispatchEventImpl(Component.java:2593)
at java.awt.Container.dispatchEventImpl(Container.java:1213)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:245
)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
at java.awt.Container.dispatchEventImpl(Container.java:1200)
at java.awt.Window.dispatchEventImpl(Window.java:914)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchT
read.java:131)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThr
ad.java:98)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
Exception occurred during event dispatching:
java.lang.NumberFormatException:
at java.lang.Integer.parseInt(Integer.java:435)
at java.lang.Integer.parseInt(Integer.java:463)
at StudentTracker$MyActionListener.actionPerformed(StudentTracker.java:
41)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1
50)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstr
ctButton.java:1504)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonMode
.java:378)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:25
)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButton
istener.java:216)
at java.awt.Component.processMouseEvent(Component.java:3715)
at java.awt.Component.processEvent(Component.java:3544)
at java.awt.Container.processEvent(Container.java:1164)
at java.awt.Component.dispatchEventImpl(Component.java:2593)
at java.awt.Container.dispatchEventImpl(Container.java:1213)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:245
)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
at java.awt.Container.dispatchEventImpl(Container.java:1200)
at java.awt.Window.dispatchEventImpl(Window.java:914)
at java.awt.Component.dispatchEvent(Component.java:2497)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchT
read.java:131)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThr
ad.java:98)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
Press any key to continue...
I just figured out one problem I converted into type float instead of double and it works, but I still have a question listed above about #2,also why is do i have to enter grade values inito all boxes in order for a button to work, if i leave one blank it doesn't workthanx