Welcome to Dream.In.Code
Become a Java Expert!

Join 149,481 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,395 people online right now. Registration is fast and FREE... Join Now!




How do parse a double or integer in JTextBox

 
Reply to this topicStart new topic

How do parse a double or integer in JTextBox

dbrine
17 May, 2007 - 05:16 PM
Post #1

New D.I.C Head
*

Joined: 25 Apr, 2007
Posts: 48


My Contributions
I've been looking and trying to figure out how to parse a double and intger in a JTextBox.....




User is offlineProfile CardPM
+Quote Post

keems21
RE: How Do Parse A Double Or Integer In JTextBox
17 May, 2007 - 08:30 PM
Post #2

D.I.C Head
Group Icon

Joined: 3 Feb, 2007
Posts: 183



Thanked: 2 times
Dream Kudos: 25
My Contributions
Do you mean a JTextField?
If that's it, you could probably use something like this:
CODE

JTextField textField = new JTextField();
String text = textField.getText();
int fieldVal = Integer.parseInt(text);


You'll probably need to throw in some error catching stuff, but that should get the job done.
User is offlineProfile CardPM
+Quote Post

dbrine
RE: How Do Parse A Double Or Integer In JTextBox
18 May, 2007 - 06:19 PM
Post #3

New D.I.C Head
*

Joined: 25 Apr, 2007
Posts: 48


My Contributions
I tried that but didn't work as excepted. Here is the code I have. Can you look at it and point me in the right direction?


CODE

/*
Chapter 8:            BillPayer Power & Light
Programmer:            Joy Starks
Date:                November 19, 2004
Programmer Name:    BillPayer
*/

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;

public class BillPayer extends JFrame implements ActionListener
{
    //Delcare output stream
    DataOutputStream output;

    //construct a panel for each row
    JPanel firstRow = new JPanel();
    JPanel secondRow = new JPanel();
    JPanel thirdRow = new JPanel();
    JPanel fourthRow = new JPanel();
    JPanel fifthRow = new JPanel();
    JPanel sixthRow = new JPanel();
    JPanel seventhRow = new JPanel();
    JPanel eighthRow = new JPanel();

    //construct a panel for the fields and buttons
    JPanel fieldPanel = new JPanel();
    JPanel buttonPanel = new JPanel();

    //construct labels and text boxes
    JLabel accntNumLabel = new JLabel("Account Number:                          ");
        JTextField accntNum = new JTextField(15);
    JLabel pmtLabel = new JLabel("Payment Amount:");
        JTextField pmt = new JTextField(10);
    JLabel firstNameLabel = new JLabel("First Name:                 ");
        JTextField firstName = new JTextField(10);
    JLabel lastNameLabel = new JLabel("Last Name:");
        JTextField lastName= new JTextField(20);
    JLabel addressLabel = new JLabel("Address:");
        JTextField address = new JTextField(35);
    JLabel cityLabel = new JLabel("City:                              ");
        JTextField city = new JTextField(10);
    JLabel stateLabel = new JLabel("State:   ");
        JTextField state = new JTextField(2);
    JLabel zipLabel = new JLabel("Zip:");
        JTextField zip = new JTextField(9);

    //construct button
    JButton submitButton = new JButton("Submit");

    public static void main(String[] args)
    {
        //set the look and feel of the interface
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "The UIManager could not set the Look and Feel for this application.","Error", JOptionPane.INFORMATION_MESSAGE);
        }

        BillPayer f= new BillPayer();
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        f.setSize(450,300);
        f.setTitle("Crandall Power and Light Payments");
        f.setResizable(false);
        f.setLocation(200,200);
        f.setVisible(true);
    }

    public BillPayer()
    {
        Container c = getContentPane();
        c.setLayout((new BorderLayout()));
        fieldPanel.setLayout(new GridLayout(8,1));
        FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
            firstRow.setLayout(rowSetup);
            secondRow.setLayout(rowSetup);
            thirdRow.setLayout(rowSetup);
            fourthRow.setLayout(rowSetup);
            fifthRow.setLayout(rowSetup);
            sixthRow.setLayout(rowSetup);
            seventhRow.setLayout(rowSetup);
            eighthRow.setLayout(rowSetup);
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        //add fields to rows
        firstRow.add(accntNumLabel);
        firstRow.add(pmtLabel);

        secondRow.add(accntNum);
        secondRow.add(pmt);

        thirdRow.add(firstNameLabel);
        thirdRow.add(lastNameLabel);
        thirdRow.add(lastNameLabel);

        fourthRow.add(firstName);
        fourthRow.add(lastName);

        fifthRow.add(addressLabel);

        sixthRow.add(address);

        seventhRow.add(cityLabel);
        seventhRow.add(stateLabel);
        seventhRow.add(zipLabel);

        eighthRow.add(city);
        eighthRow.add(state);
        eighthRow.add(zip);

        //add rows to panel
        fieldPanel.add(firstRow);
        fieldPanel.add(secondRow);
        fieldPanel.add(thirdRow);
        fieldPanel.add(fourthRow);
        fieldPanel.add(fifthRow);
        fieldPanel.add(sixthRow);
        fieldPanel.add(seventhRow);
        fieldPanel.add(eighthRow);


        //add button to panel
        buttonPanel.add(submitButton);

        //add panels to frame
        c.add(fieldPanel, BorderLayout.CENTER);
        c.add(buttonPanel, BorderLayout.SOUTH);

        //add functionality to buttons
        submitButton.addActionListener(this);

    //Get current date and open the file
    Date today = new Date();
    SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
    String filename = "payments" + myFormat.format(today);

    try
    {
        output = new DataOutputStream(new FileOutputStream(filename));
    }
    catch(IOException io)
    {
        JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error", JOptionPane.INFORMATION_MESSAGE);

        System.exit(1);
    }

    addWindowListener(
        new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit and submit the file?", "File Submission", JOptionPane.YES_NO_OPTION);
                if (answer == JOptionPane.YES_OPTION)
                    System.exit(0);
            }
        }
    );
}

    public void actionPerformed(ActionEvent e)
    {
        String arg = e.getActionCommand();

        if (checkFields())
        {
            try
            {
                output.writeUTF(accntNum.getText());
                output.writeUTF(pmt.getText());
                output.writeUTF(firstName.getText());
                output.writeUTF(lastName.getText());
                output.writeUTF(address.getText());
                output.writeUTF(city.getText());
                output.writeUTF(state.getText());
                output.writeUTF(zip.getText());

                JOptionPane.showMessageDialog(null, "The payment information has been saved.", "Submission Successful", JOptionPane.INFORMATION_MESSAGE);
            }
            catch(IOException c)
            {
                System.exit(1);
            }
            clearFields();
        }
    }

    public boolean checkFields()
    {
        if ((accntNum.getText().compareTo("")<1)  ||
            (pmt.getText().compareTo("")<1)       ||
            (firstName.getText().compareTo("")<1) ||
            (lastName.getText().compareTo("")<1)  ||
            (address.getText().compareTo("")<1)   ||
            (city.getText().compareTo("")<1)      ||
            (state.getText().compareTo("")<1)     ||
            (zip.getText().compareTo("")<1))
        {
            JOptionPane.showMessageDialog(null, "You must complete all fields.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else
        {
                if ((accntNum.getText().compareTo("") !=10))
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.setText("");

                if (state.getText().compareTo("") != 2)
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.setText("");

                String pmtAmount = pmt.getText();
                double pmtVal = Double.parseDouble(pmtAmount);
                JOptionPane.showMessageDialog(null, "Please enter only numbers.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);

                String zipCode = zip.getText();
                int zipCD = Integer.parseInt(zipCode);
                JOptionPane.showMessageDialog(null, "please enter only numbers.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);

                return false;
        }
    }

    public void clearFields()
    {
        //clear fields and reset the focus
        accntNum.setText("");
        pmt.setText("");
        firstName.setText("");
        lastName.setText("");
        address.setText("");
        city.setText("");
        state.setText("");
        zip.setText("");
        accntNum.requestFocus();
    }
}




QUOTE(keems21 @ 17 May, 2007 - 09:30 PM) *

Do you mean a JTextField?
If that's it, you could probably use something like this:
CODE

JTextField textField = new JTextField();
String text = textField.getText();
int fieldVal = Integer.parseInt(text);


You'll probably need to throw in some error catching stuff, but that should get the job done.


User is offlineProfile CardPM
+Quote Post

keems21
RE: How Do Parse A Double Or Integer In JTextBox
18 May, 2007 - 08:26 PM
Post #4

D.I.C Head
Group Icon

Joined: 3 Feb, 2007
Posts: 183



Thanked: 2 times
Dream Kudos: 25
My Contributions
OK, here's what I added to your code to get it to take a String from a text box and make it into an int:
CODE
int zipint = Integer.parseInt(zip.getText());
                System.out.println(zipint);


I added it inside of your actionEvent method and it worked like a charm. The only thing that I had to do was get rid of the if statement because your method checkfields() was a little confusing for me.

To do the same thing for double, take everywhere I used the word "int" and replace it with "double" (and change the name of the textField you want to take the String from.

Enjoy.

Edit:
Oh yeah, and the print statement was only put there to make sure that everything worked ok.

This post has been edited by keems21: 18 May, 2007 - 08:27 PM
User is offlineProfile CardPM
+Quote Post

dbrine
RE: How Do Parse A Double Or Integer In JTextBox
19 May, 2007 - 12:39 PM
Post #5

New D.I.C Head
*

Joined: 25 Apr, 2007
Posts: 48


My Contributions
here is what I have so far. I got it to parse. I couldn't get it to work the way you said. Can you post the code (I've made allot of changes to the original code)? When I run it add it comes across an error I want it to refocus to the bad field(which it does) and then delete the comtents of that field only. My code does most of that except it also deleted the account number, payment and state.

CODE


import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;

public class BillPayer extends JFrame implements ActionListener
{
    //Delcare output stream
    DataOutputStream output;

    //construct a panel for each row
    JPanel firstRow = new JPanel();
    JPanel secondRow = new JPanel();
    JPanel thirdRow = new JPanel();
    JPanel fourthRow = new JPanel();
    JPanel fifthRow = new JPanel();
    JPanel sixthRow = new JPanel();
    JPanel seventhRow = new JPanel();
    JPanel eighthRow = new JPanel();

    //construct a panel for the fields and buttons
    JPanel fieldPanel = new JPanel();
    JPanel buttonPanel = new JPanel();

    //construct labels and text boxes
    JLabel accntNumLabel = new JLabel("Account Number:                          ");
        JTextField accntNum = new JTextField(15);
    JLabel pmtLabel = new JLabel("Payment Amount:");
        JTextField pmt = new JTextField(10);
    JLabel firstNameLabel = new JLabel("First Name:                 ");
        JTextField firstName = new JTextField(10);
    JLabel lastNameLabel = new JLabel("Last Name:");
        JTextField lastName= new JTextField(20);
    JLabel addressLabel = new JLabel("Address:");
        JTextField address = new JTextField(35);
    JLabel cityLabel = new JLabel("City:                              ");
        JTextField city = new JTextField(10);
    JLabel stateLabel = new JLabel("State:   ");
        JTextField state = new JTextField(2);
    JLabel zipLabel = new JLabel("Zip:");
        JTextField zip = new JTextField(9);

    //construct button
    JButton submitButton = new JButton("Submit");

    public static void main(String[] args)
    {
        //set the look and feel of the interface
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "The UIManager could not set the Look and Feel for this application.","Error", JOptionPane.INFORMATION_MESSAGE);
        }

        BillPayer f= new BillPayer();
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        f.setSize(450,300);
        f.setTitle("Crandall Power and Light Payments");
        f.setResizable(false);
        f.setLocation(200,200);
        f.setVisible(true);
    }

    public BillPayer()
    {
        Container c = getContentPane();
        c.setLayout((new BorderLayout()));
        fieldPanel.setLayout(new GridLayout(8,1));
        FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
            firstRow.setLayout(rowSetup);
            secondRow.setLayout(rowSetup);
            thirdRow.setLayout(rowSetup);
            fourthRow.setLayout(rowSetup);
            fifthRow.setLayout(rowSetup);
            sixthRow.setLayout(rowSetup);
            seventhRow.setLayout(rowSetup);
            eighthRow.setLayout(rowSetup);
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        //add fields to rows
        firstRow.add(accntNumLabel);
        firstRow.add(pmtLabel);

        secondRow.add(accntNum);
        secondRow.add(pmt);

        thirdRow.add(firstNameLabel);
        thirdRow.add(lastNameLabel);
        thirdRow.add(lastNameLabel);

        fourthRow.add(firstName);
        fourthRow.add(lastName);

        fifthRow.add(addressLabel);

        sixthRow.add(address);

        seventhRow.add(cityLabel);
        seventhRow.add(stateLabel);
        seventhRow.add(zipLabel);

        eighthRow.add(city);
        eighthRow.add(state);
        eighthRow.add(zip);

        //add rows to panel
        fieldPanel.add(firstRow);
        fieldPanel.add(secondRow);
        fieldPanel.add(thirdRow);
        fieldPanel.add(fourthRow);
        fieldPanel.add(fifthRow);
        fieldPanel.add(sixthRow);
        fieldPanel.add(seventhRow);
        fieldPanel.add(eighthRow);


        //add button to panel
        buttonPanel.add(submitButton);

        //add panels to frame
        c.add(fieldPanel, BorderLayout.CENTER);
        c.add(buttonPanel, BorderLayout.SOUTH);

        //add functionality to buttons
        submitButton.addActionListener(this);

    //Get current date and open the file
    Date today = new Date();
    SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
    String filename = "payments" + myFormat.format(today);

    try
    {
        output = new DataOutputStream(new FileOutputStream(filename));
    }
    catch(IOException io)
    {
        JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error", JOptionPane.INFORMATION_MESSAGE);

        System.exit(1);
    }

    addWindowListener(
        new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit and submit the file?", "File Submission", JOptionPane.YES_NO_OPTION);
                if (answer == JOptionPane.YES_OPTION)
                    System.exit(0);
            }
        }
    );
}

    public void actionPerformed(ActionEvent e)
    {
        String arg = e.getActionCommand();

        if (checkFields())
        {
            try
            {
                output.writeUTF(accntNum.getText());
                output.writeUTF(pmt.getText());
                output.writeUTF(firstName.getText());
                output.writeUTF(lastName.getText());
                output.writeUTF(address.getText());
                output.writeUTF(city.getText());
                output.writeUTF(state.getText());
                output.writeUTF(zip.getText());

                JOptionPane.showMessageDialog(null, "The payment information has been saved.", "Submission Successful", JOptionPane.INFORMATION_MESSAGE);
            }
            catch(IOException c)
            {
                System.exit(1);

            }
            clearFields();
        }
    }

    public boolean checkFields()
    {
        if ((accntNum.getText().compareTo("")<1)  ||
            (pmt.getText().compareTo("")<1)       ||
            (firstName.getText().compareTo("")<1) ||
            (lastName.getText().compareTo("")<1)  ||
            (address.getText().compareTo("")<1)   ||
            (city.getText().compareTo("")<1)      ||
            (state.getText().compareTo("")<1)     ||
            (zip.getText().compareTo("")<1))
        {
            JOptionPane.showMessageDialog(null, "You must complete all fields.", "Data Entry Error", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else
        {
                if ((accntNum.getText().compareTo("") !=10))
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Account Number Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.requestFocus();
                accntNum.setText("");

                if (state.getText().compareTo("") != 2)
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "State Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.requestFocus();
                state.setText("");

                try
                {
                    double pmtdouble = Double.parseDouble(pmt.getText());
                }
                catch(NumberFormatException e)
                {
                    JOptionPane.showMessageDialog(null, "Please enter only numbers.", "Payment Amount Data Entry Error", JOptionPane.WARNING_MESSAGE);
                    pmt.requestFocus();
                    pmt.setText("");
                }
                try
                {
                    int zipint = Integer.parseInt(zip.getText());
                }
                catch(NumberFormatException e)
                {
                    JOptionPane.showMessageDialog(null, "please enter only numbers in zip.", "Zip Code Data Entry Error", JOptionPane.WARNING_MESSAGE);
                    zip.requestFocus();
                    zip.setText("");
                }
                return false;
        }
    }

    public void clearFields()
    {
        //clear fields and reset the focus
        accntNum.setText("");
        pmt.setText("");
        firstName.setText("");
        lastName.setText("");
        address.setText("");
        city.setText("");
        state.setText("");
        zip.setText("");
        accntNum.requestFocus();
    }
}





QUOTE(keems21 @ 18 May, 2007 - 09:26 PM) *

OK, here's what I added to your code to get it to take a String from a text box and make it into an int:
CODE
int zipint = Integer.parseInt(zip.getText());
                System.out.println(zipint);


I added it inside of your actionEvent method and it worked like a charm. The only thing that I had to do was get rid of the if statement because your method checkfields() was a little confusing for me.

To do the same thing for double, take everywhere I used the word "int" and replace it with "double" (and change the name of the textField you want to take the String from.

Enjoy.

Edit:
Oh yeah, and the print statement was only put there to make sure that everything worked ok.


User is offlineProfile CardPM
+Quote Post

keems21
RE: How Do Parse A Double Or Integer In JTextBox
19 May, 2007 - 03:04 PM
Post #6

D.I.C Head
Group Icon

Joined: 3 Feb, 2007
Posts: 183



Thanked: 2 times
Dream Kudos: 25
My Contributions
Hey, you did a nice job of implementing the code that I gave to you.

I'm still not sure that I fully understand what you're trying to accomplish with your code, but I do see something that you may have not intended to do.

Check this section of code in your checkFields() method:
CODE
if ((accntNum.getText().compareTo("") !=10))
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Account Number Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.requestFocus();
                accntNum.setText("");

                if (state.getText().compareTo("") != 2)
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "State Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.requestFocus();
                state.setText("");


First of all, I think that you want to have both of those if statements in brackets. The way that you have it now, if either of those is true, then the JOptionPane is being displayed, then both fields are being cleard regardless of whether of not the if statement was executed.

The second thing is your use of compare(). This is just a guess, but I'm thinking that you mean for the account number to be 10 numbers, and for the state abreviation to be two letters. I think that a better method to use would be the length().

So try this and tell me how it works out for you:
CODE

if ((accntNum.getText().length() !=10))
{
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Account Number Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.requestFocus();
                accntNum.setText("");
}
if (state.getText().length() != 2)
{
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "State Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.requestFocus();
                state.setText("");
}

User is offlineProfile CardPM
+Quote Post

dbrine
RE: How Do Parse A Double Or Integer In JTextBox
19 May, 2007 - 04:53 PM
Post #7

New D.I.C Head
*

Joined: 25 Apr, 2007
Posts: 48


My Contributions
THANKS!!! That seemed to do it. I was so close but just couldn't think of what I was doing wrong.


QUOTE(keems21 @ 19 May, 2007 - 04:04 PM) *

Hey, you did a nice job of implementing the code that I gave to you.

I'm still not sure that I fully understand what you're trying to accomplish with your code, but I do see something that you may have not intended to do.

Check this section of code in your checkFields() method:
CODE
if ((accntNum.getText().compareTo("") !=10))
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Account Number Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.requestFocus();
                accntNum.setText("");

                if (state.getText().compareTo("") != 2)
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "State Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.requestFocus();
                state.setText("");


First of all, I think that you want to have both of those if statements in brackets. The way that you have it now, if either of those is true, then the JOptionPane is being displayed, then both fields are being cleard regardless of whether of not the if statement was executed.

The second thing is your use of compare(). This is just a guess, but I'm thinking that you mean for the account number to be 10 numbers, and for the state abreviation to be two letters. I think that a better method to use would be the length().

So try this and tell me how it works out for you:
CODE

if ((accntNum.getText().length() !=10))
{
                JOptionPane.showMessageDialog(null, "Account Number Wrong Length.", "Account Number Data Entry Error", JOptionPane.WARNING_MESSAGE);
                accntNum.requestFocus();
                accntNum.setText("");
}
if (state.getText().length() != 2)
{
                JOptionPane.showMessageDialog(null, "Please only 2 letters for the state.", "State Data Entry Error", JOptionPane.WARNING_MESSAGE);
                state.requestFocus();
                state.setText("");
}



User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 04:27PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month