Anyone have/know of a method that would format a textbox?

Hi all,
I'm currently trying to make a java tax program. It's not finished, obviously. I'm using ready to program. Here is what I want to do. I want to take the amount in the subtotal box, and as the user is typing, after the key is pressed, the program will check to see if it is an actual number, and if there are strings in it, the computer will automatically knock them out and leave a number. Now, this is supposed to be a currency amount... Any suggestions? Here is my code:
// The "JavaTax" class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.text.DecimalFormat;
public class JavaTax extends JFrame
    private Container contents;
    private JLabel amount, total, gsttotal, psttotal, hsttotal, qsttotal;
    private JTextField amountBox, totalBox, gsttotalBox, psttotalBox, hsttotalBox, qsttotalBox;
    private JPanel totals, selection;
    private JButton calc;
    private JCheckBox gst, hst, pst, qst;
    private JComboBox pstProvinces, hstProvinces;
    private String provincesPST[] = new String [5];
    private String provincesHST[] = new String [3];
    private double QSTRATE = 7.5;
    double subTotal = 0;
    public JavaTax ()
        super ("Java Tax");
        contents = getContentPane ();
        contents.setLayout (new BorderLayout ());
        provincesPST [0] = "British Columbia (7%)";
        provincesPST [1] = "Saskatchewan (5%)";
        provincesPST [2] = "Manitoba (7%)";
        provincesPST [3] = "Ontario (8%)";
        provincesPST [4] = "Prince Edward Island (10%)";
        provincesHST [0] = "New Brunswick (13%)";
        provincesHST [1] = "Newfoundland (13%)";
        provincesHST [2] = "Nova Scotia (13%)";
        hsttotal = new JLabel ("HST Total:", JLabel.RIGHT);
        qsttotal = new JLabel ("QST Total:", JLabel.RIGHT);
        gsttotal = new JLabel ("GST Total:", JLabel.RIGHT);
        psttotal = new JLabel ("PST Total:", JLabel.RIGHT);
        total = new JLabel ("Total:", JLabel.RIGHT);
        amount = new JLabel ("Amount:", JLabel.RIGHT);
        psttotalBox = new JTextField ("", 10);
        psttotalBox.setEditable (false);
        hsttotalBox = new JTextField ("", 10);
        hsttotalBox.setEditable (false);
        gsttotalBox = new JTextField ("", 10);
        gsttotalBox.setEditable (false);
        qsttotalBox = new JTextField ("", 10);
        qsttotalBox.setEditable (false);
        totalBox = new JTextField ("", 10);
        amountBox = new JTextField ("", 10);
        calc = new JButton ("Calculate");
        gst = new JCheckBox ("GST");
        pst = new JCheckBox ("PST");
        hst = new JCheckBox ("HST");
        qst = new JCheckBox ("QST");
        pstProvinces = new JComboBox (provincesPST);
        hstProvinces = new JComboBox (provincesHST);
        //HST only in NB, Newfoundland and NS (all 13%)
        //QST only in Quebec (7.5%)
        // sample = new JLabel (new ImageIcon("file.jpg"))
        hsttotal.setForeground (Color.BLACK);
        psttotal.setForeground (Color.BLACK);
        gsttotal.setForeground (Color.BLACK);
        total.setForeground (Color.BLACK);
        amount.setForeground (Color.BLACK);
        hsttotal.setOpaque (true);
        gsttotal.setOpaque (true);
        psttotal.setOpaque (true);
        total.setOpaque (true);
        amount.setOpaque (true);
        totals = new JPanel ();
        totals.setLayout (new GridLayout (6, 2, 2, 10));
        contents.add (totals, BorderLayout.WEST);
        totals.add (amount);
        totals.add (amountBox);
        totals.add (gsttotal);
        totals.add (gsttotalBox);
        totals.add (psttotal);
        totals.add (psttotalBox);
        totals.add (hsttotal);
        totals.add (hsttotalBox);
        totals.add (qsttotal);
        totals.add (qsttotalBox);
        totals.add (total);
        totals.add (totalBox);
        selection = new JPanel (new GridLayout (7, 1, 2, 10));
        contents.add (selection, BorderLayout.EAST);
        selection.add (gst);
        selection.add (pst);
        selection.add (pstProvinces);
        selection.add (hst);
        selection.add (hstProvinces);
        selection.add (qst);
        selection.add (calc);
        setSize (500, 350);
        setVisible (true);
        NormalTaxHandler nth = new NormalTaxHandler ();
        SpecialTaxHandler sth = new SpecialTaxHandler ();
        TextFieldHandler tfh = new TextFieldHandler ();
        gst.addItemListener (nth);
        pst.addItemListener (nth);
        hst.addItemListener (sth);
        qst.addItemListener (sth);
        amountBox.addKeyListener (tfh);
    public static void main (String[] args)
        JavaTax guey = new JavaTax ();
        guey.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } // main method
    public class TextFieldHandler implements KeyListener
        //implementation of KeyListener methods
        public void keyPressed (KeyEvent e)
        public void keyReleased (KeyEvent e)
            check (e);
        public void keyTyped (KeyEvent e)
        public void check (KeyEvent e)
            try
                subTotal = Double.parseDouble (amountBox.getText ());
                DecimalFormat df = new DecimalFormat ("#.##");
                //subTotal =
                //subTotal = subTotal * 100;
                //subTotal = ((int)subTotal)/100;
                amountBox.setText (String.valueOf (df.format (subTotal)));
                subTotal = Double.parseDouble (amountBox.getText ());
            catch (NumberFormatException nfe)
                DecimalFormat df = new DecimalFormat ("#.##");
                amountBox.setText (String.valueOf (df.format (subTotal)));
                subTotal = Double.parseDouble (amountBox.getText ());
            subTotal = Double.parseDouble (amount);
            subTotal = subTotal * 100;
            subTotal = (int) subTotal / 100;
    private class NormalTaxHandler implements ItemListener
        public void itemStateChanged (ItemEvent ie)
            JCheckBox source = (JCheckBox) ie.getSource ();
            // If the object is selected . . .
            if (ie.getStateChange () == ItemEvent.SELECTED)
                qst.setVisible (false);
                hst.setVisible (false);
                hstProvinces.setVisible (false);
            else
                if (pst.isSelected () == false && gst.isSelected () == false)
                    qst.setVisible (true);
                    hst.setVisible (true);
                    hstProvinces.setVisible (true);
    private class SpecialTaxHandler implements ItemListener
        public void itemStateChanged (ItemEvent ie)
            JCheckBox source = (JCheckBox) ie.getSource ();
            if (ie.getStateChange () == ItemEvent.SELECTED)
                gst.setVisible (false);
                pst.setVisible (false);
                pstProvinces.setVisible (false);
                if (qst.isSelected () == true && hst.isSelected () == false)
                    hst.setVisible (false);
                    hstProvinces.setVisible (false);
                else if (hst.isSelected () == true && qst.isSelected () == false)
                    qst.setVisible (false);
            else
                if (hst.isSelected () == false || qst.isSelected () == false)
                    gst.setVisible (true);
                    pst.setVisible (true);
                    pstProvinces.setVisible (true);
                    hst.setVisible (true);
                    qst.setVisible (true);
                    hstProvinces.setVisible (true);
     * Create a MaskFormatter for FormattedTextFields
    protected MaskFormatter createFormatter (String s)
        MaskFormatter formatter = null;
        try
            formatter = new MaskFormatter (s);
        } // try
        catch (java.text.ParseException exc)
        } // catch
        return formatter;
    } // MaskFormatter method
} // GUI class

You can use Integer.parseInt(String) (or Double.parseDouble(String), etc.) to check if the String represents a number.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
If it doesn't, you can use Character.isDigit(char) to check each char, and substring them out if they aren't digits. Then parse it again.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isDigit(char)

Similar Messages

  • Can anyone help me write a script that would click "get info" and then "enter" on each movie in my itunes library? I am asking because my itunes 11 repeatedly loses the artwork to my movies in my itunes library.

    Can anyone help me write a script that would click "get info" and then "enter" on each movie in my itunes library? I am asking because my itunes 11 repeatedly loses the artwork to my movies in my itunes library. I can restore the artwork (and make my apple tv see the movie exists as well) by going into the movie library and clicking on each movie by hand, slecting get info, and then selecting enter. Now doing this 10 times in 20 days was fun and all BUT I would really like to automate the process so everytime itunes screws it up I can fix it easier.
    I saw this example of an itunes script that restores artwork for music
    tell application "iTunes" set theSelection to selection repeat with i from 1 to count of theSelection tell (item i of theSelection) set artworkCount to count of artwork repeat artworkCount times set theArtwork to data of artwork 1 delete artwork 1 set data of artwork artworkCount to theArtwork end repeat end tell end repeat end tell
    but I need to tweak this to fit my needs for simply clicking the "get info" button and "enter" in the movie library rather than all the stuff this guy has listed. Any ideas or help on writing this? Thanks.

    Try assigning Queen as the Album Artist on the compilations in iTunes on your computer.

  • Does anyone have a sample implementation plan that can be shared?  High level?

    Does anyone have a sample implementation plan that can be shared?  High level?

    You will probably need to inquire with a VMware consultant to get this kind of information.  VMware depends on these people to make sure they keep the reputation of the software at a very high level.  
    They will have access to various free tools to help large and small scale deployments.  Tools like VMware Health Check Script and the ESX deployment tool.
    If you find this information useful, please award points for
    "correct"
    or "helpful".
    Wes Hinshaw
    www.myvmland.com

  • Does anyone have a list of tracks that came free with itunes from the year 2000 onward, from memory they were on the G4 Tower OS install discs?

    Does anyone have a list of tracks that came free with itunes from the year 2000 onward, from memory they were on the G4 Tower OS install discs?

    Does anyone have a list of tracks that came free with itunes from the year 2000 onward, from memory they were on the G4 Tower OS install discs?

  • Does anyone have a spiraling rainbow image that appears and slow down you computer?

    does anyone have a spiraling rainbow image that appears and seems to slow down the computer?

    Everyone does at one point or another. Please be a little more specific about when this occurs. Also you may find Spinning Beach Ball of Death useful to track down the reason yours is occurring.

  • I have apple id but i have to create payment method that i don't wish to

    I have apple id but i have to create payment method that i don't wish to

    Silentcontrolmaycare,
    why do you have to create a payment method at all?

  • I have an external hard drive that was formatted by a PC and has files and directories etc. I want to format it and use it on my IMAC for backup but I can't seem to write to it nor can I delete current content. How do I initialize it for use with the MAC?

    I have an external hard drive that was formatted by a PC and has files and directories copied to it etc. I want to use it on my IMAC for backup. I see it on my my IMAC . I can open files etc.  But I can't seem to write to it nor can I delete current content. I don't care if I lose current content. How do I initialize it for use with the MAC?

    You can't write to it because it's formatted as NTFS which OS X will read but not write to. If you want to continue using the drive with both a PC and OS X you will need to download and install NTFS-3G so you can then write to it from your Mac. You can get NTFS-3G at:
    http://www.macupdate.com/app/mac/24481/ntfs-3g
    If you want to use the drive exclusively with your Mac then move the data off it and reformat it in Disk Utility (Applications - Utilities - Disk Utilities) as Mac OS Extended (Journaled.)

  • Trying to install Windows 7 on my new computer - Does anyone know someone within HP that would help?

    I am trying to downgrade from Win 8.1 to Win 7 and so far I am not having any luck completing the downgrade.
    (HP Envy 700-430qe).
                           As you can see, several in this forum have tried to help! 
                    Does anyone know of a department within HP that would help? 
                          ( I tried HP tec support, but they will not touch it. They say "out of our scope")
    I have completely wiped my 2 tb hard drive using Diskpart/clean all. I then installed my Win 7 disk directly on to
    a formatted 100 gb partition on the drive, but as always, the installation goes almost 90 % of the way with no problem, then soon
    after the reboot it stops at the same point as it does when I try a dual boot install or a downgrade install. Very very
    frustrating. 
    Thanks, Brad

    Hi, Brad:
    The only suggestion I can offer would be to try this...
    Download the drivers from this link below (first file listed -- 64 bit).
    https://downloadcenter.intel.com/Detail_Desc.aspx?​agr=Y&ProdId=2101&DwnldID=23060&keyword=Intel+Rap...
    Extract (copy) the files onto a usb flash drive without any folders.
    With the flash drive in a USB2 port and W7 installation media in the machine, boot from the W7 installation media.
    After you select the install now option, select the Drive Options - Advanced menu, then select the Load Driver option.
    You should now see the storage driver files listed.
    If you check the box, it will only include the compatible driver.
    Follow the prompts and hopefully, W7 will install.

  • Does anyone have a report using cfdocument that produces a ledger type report with column headings?

    I need to see some sample source code of a report with column headings and detail data.  I can't get my column titles in the header to line up with the detail no matter what I do.  Can anyone spare me a good sample?
    I have tried to use tables to specify both col headings and detail, but no chance to get them to line up.  There has to be a way.  I can't use the report builder because I need more control of when page breaks print, what data is on each line, etc.  Hopefully some kind soul out there has a good sample.
    Thanks!
    Dave

    Your MBP is actually a mid-2010, not a 2008. That's what the 6,2 model indicates.There's an issue with the graphics module on that machine. There was a program in place to replace the motherboard within 3 years of purchase, but you're probably outside of that. Some folks have supposedly gotten theirs changed outside of that period, so you can try.
    http://support.apple.com/kb/TS4088?viewlocale=en_US&locale=en_US
    What you can do to use it is download gfxstatus from http:gfx.io and force the graphics to Intel. That would affect your work with Final Cut, but at least you might be able to use the machine.

  • Does anyone have a new MacBook Pro that makes a buzzing sound on startup?

    My new (60 days) MacBook Pro makes a buzzing sound on startup- does anyone else have this issue? Thanks!

    Keep at the Genius Bar.
    For one, you have a default 1 year warranty, which you do not want to let expire.
    For another, that chine is a critical part of the system, that for some is an annoyance but at least it sticks around.
    At some point, they have to either fix it or give you another (at least in my opinion they will eventually have to give me on that chimes).
    Make a very good clone before you go back in.  CarbonCopyClone ($40 download).  You will need to clone it back onto a new system eventually, I suspect.

  • Does anyone have script or fast method to add transp. to que?

    I have isolated a server for a GoLive Rehearsal and would like to load MANY transports into this new server, rather than load them all one by one (ie. add to que, then transport) , does anyone know of a quicker way to do the WHOLE lot at once?
    Thanks in advance for saving me time
    Maria

    Ken , many, many thanks!
    I have actually broken down the import scripts to about 5 with about 200 entries each.
    I do find that about a dozen entires have errored with parameter has wrong length, the odd thing is all the TPIMPORT statements were created from the same Excell macro. ie., the transports were sequentially entered in an excell spreadsheet to ensure the correct sequence
    I then created a macro (as recommended from this thread) that created a large script for import
    I took this one step further and split this large file into smaller files/scripts of about 200 entries. 
    I have only run the first of 5 entries, and it is puzzling to me why I get the error 'parameter has wrong length'  the statements are cookie cutter statements, exactly the same. see error below
    E:\SAP Software\SAPPHYR Transport Log\TPImport Scripts>tp import ECDK901251 ECP client=200 U126 pf=d:\usr\sap\transcopy\bin\TP_DOMAIN_ECP.PFL
    This is tp version 372.04.40 (release 700, unicode enabled)
    ERROR: : parameter U126 has wrong length
    And a successfully statement result below
    E:\SAP Software\SAPPHYR Transport Log\TPImport Scripts>tp import ECDK900229 ECP client=200 U126 pf=d:\usr\sap\transcopy\bin\TP_DOMAIN_ECP.PFL
    This is tp version 372.04.40 (release 700, unicode enabled)
    This is R3trans.exe version 6.14 (release 700 - 28.07.08 - 15:52:00).
    unicode enabled version
    R3trans.exe finished (0004).
    tp finished with return code: 4
    meaning:
      A tool used by tp produced warnings
    You can observe the statements are identical starting at "tp import ECDKxxxxx ECP etc...
    any ideas why they would error?
    Regards,
    Maria

  • Lightroom does not recognize the raw format of files loading from my Nikon AW1 and loads them as jpegs. I know there are updates that would allow this camera to be recognized as shooting raw but I haven't been able to work it out. Any help out there?

    Lightroom does not recognize the raw files (necs?) coming in from my Nikon AW1. It loads them as jpegs. I know it is possible to update Lightroom so it knows my Nikon but I can't get it to work.
    I would like files to be loaded as .dng.

    update by downloading the files directly and then applying them for lr 4 and earlier,  http://www.adobe.com/downloads/updates/
    for lr 5.7.1, the last lr 5 update, use the below link:
    Downloadable installation files available:
    Suites and Programs:  CC 2014 | CC | CS6 | CS5.5 | CS5 | CS4, CS4 Web Standard | CS3
    Acrobat:  XI, X | 9,8 | 9 standard
    Premiere Elements:  13 | 12 | 11, 10 | 9, 8, 7 win | 8 mac | 7 mac
    Photoshop Elements:  13 |12 | 11, 10 | 9,8,7 win | 8 mac | 7 mac
    Lightroom:  6| 5.7.1| 5 | 4 | 3
    Captivate:  8 | 7 | 6 | 5.5, 5 | 1
    Contribute:  CS5 | CS4, CS3 | 3,2
    FrameMaker:  12, 11, 10, 9, 8, 7.2
    Download and installation help for Adobe links
    Download and installation help for Prodesigntools links are listed on most linked pages.  They are critical; especially steps 1, 2 and 3.  If you click a link that does not have those steps listed, open a second window using the Lightroom 3 link to see those 'Important Instructions'.

  • Does anyone have a new ONT unit that does not make a beeping sound if you unplug the battery?

    Hi everyone,
    Anyone here that have a Verizon FiOS ONT unit that doesn't beep when you unplug the battery? 
    Apparently the new unit alarm noise is supposed to turn off when you remove the battery. 
    FiOS ONT Battery
    I have an older model that continuously beeps if the battery is bad and if it's unplug.  Basically, the box demands a new battery.
    I called Verizon and asked them to install a new ONT Battery box because I believe the new one won't beep if the battery is unplug via their instructions.  They are coming in a couple of days.
    I just want some confirmation from users that the new box doesn't make the beeping noise if the battery is unplug.

    You can now opt out of the battery at the time of install, if you do then the tech should disable the alarm at that time. Otherwise you can disable the alarm by removing the batter and THEN rebooting the system by unplugging the power supply while the battery is unplugged. you plug it back in and the system reboots and it should recognize there is no battery upon reboot and then it should not beep anymore. If it does still beep then yeah your going to need that dispatch.

  • Anyone have a blackberry phone number that reaches out to a human being on the weekend?

    please let me know..
    thanks,
    sonja

    Hiya!
     you do get free tech support!!
     you get it via your carrier
    and if they cant fix it, they can transfer you to RIM without the fee.
    hope that helps
    1). Please thank those who help you by clicking the beside the 'Reply' button.
    2). If your issue has been solved, please resolve it by marking "Accept as Solution" on the correct post!
    3). Remember to have fun! We are all in this together!
    4). Follow me on

  • Anyone have a good printer/scanner that they like?

    Hoping to find one that is not too expensive. Please let me know if you are happy with yours. Also, if you found a bargain, please share where I can find it! Thanks

    I'm pretty much anti-all in one units. They tend to be slower, and if one part breaks the entire unit has to be sent in for repair (don't put all your eggs in one basket). When any of these consumer electronics breaks, it costs more to repair than replace.
    That said, I've had good luck with an HP Scanjet 3970 and a Epson R220 Photo printer. The advantage of the Epson which is also that of many more expensive Canon printers is that it uses multiple colored ink cartridges, meaning replacing the ink doesn't require buying a whole color cartridge at once that fills the need for all the ink cartridges. The costliest part of printers is the cost of ink, which usually mounts up to be more than the printer itself pretty quickly.

Maybe you are looking for

  • How to install windows on a system already running Arch? [SOLVED]

    Hello. I use Arch for my daily use, but I'm having a big problem, my little brother. He wants to play videogames on the laptop and that's it, I know you can do it from Arch but I honestly don't want to install Steam neither anything else than what I

  • Will Print pictures but black ink gapping

    I am having Printing trouble: At first I thought my black ink cartridge went bad, so I replace it. No fix. Black ink still leaving gaps in exactly the same place in documents. Both in The Print Shop 2 and iWork>Pages. So I took a desktop picture of d

  • Is there anyway to copy a selection of slides from one project to another and keep the linkage?

    Hi all, I've created a 'template' type project, with a selection of slides all containing styles of lessons. Some of these lessons are set up in a way that they use several slides, linked to one another in one way (or several ways). The linkage is co

  • Find dropped text?

    Hello, I produce a 2-page newsletter for my college using InDesign CS2 4.0.5; each monthly edition has 10-15 short articles submitted by faculty. My job, as editor, is simply to arrange and size/format the texts. Always there are last minute edits fr

  • Custom metadata field for GET_FILE in Content Tracker

    Hi ppl, I've trying to use content tracker to audit some actions including GET_FILE. The problem is that I need to save a custom metadata field that is not in the localdata resultset. I know that I can save all the custom metadata fields in a column