Customized JTextFiled for number autoformatting

Hi everyone,
I've been programming a customized JTextField to accept only numbers with auto-format while you're typing on it, it's almost working except some issues with decimal point. I would like you to help me to test it or give me advices to improve mi code. Thanks.
package sgpmde.forms.components;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.JTextField;
public class JNumberField extends JTextField {
    private double value = 0;
    private NumberFormat nf = NumberFormat.getCurrencyInstance();
    public JNumberField() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent evt) {
                keyTypedEvent(evt);
        this.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent evt) {
                focusGainedEvent(evt);
            @Override
            public void focusLost(FocusEvent evt) {
                focusLostEvent(evt);
    private double strToDouble(String str) {
        if (str.isEmpty()) {
            return 0.00;
        } else return Double.valueOf(str.replaceAll(",", ""));
    private String doubleToStr(double val, boolean evalDot) {
        StringBuilder num = new StringBuilder(nf.format(val));
        num.deleteCharAt(0);
        if (!getText().contains(".") && evalDot) {
            num.delete(num.length() - 3, num.length());
        return num.toString();
    private int count(String str, char chr) {
        int c = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == chr) c++;
        return c;
    private int newChars(String str1, String str2, char chr) {
        int n = count(str2, chr) - count(str1, chr);
        if (n < 0) {
            return 0;
        } else return n;
    private void insert(char chr) {
        StringBuilder num = new StringBuilder();
        if (value > 0) {
            num.append(getText());
        } else setCaretPosition(0);
        num.insert(getCaretPosition(), chr);
        value = strToDouble(num.toString());
    private void delete() {
        StringBuilder num = new StringBuilder();
        if (getText().isEmpty()) {
            value = 0;
        } else {
            num.append(getText());   
            value = strToDouble(num.toString());
    private void keyTypedEvent(KeyEvent evt) {
        char chr = evt.getKeyChar();
        evt.setKeyChar((char) 0);
        if (((chr >= '0' && chr <= '9') ||
                (chr == '.' && !getText().contains(".")))
                && getCaretPosition() != getText().length()) {
            int pos = getCaretPosition();
            insert(chr);
            String str1 = getText();
            String str2 = doubleToStr(value, false);
            setText(str2);
            setCaretPosition(pos + newChars(str1, str2, ',') + 1);
        if (chr == KeyEvent.VK_BACK_SPACE) {
            int pos = getCaretPosition();
            delete();
            String str1 = getText();
            String str2 = doubleToStr(value, true);
            setText(str2);
            int pos2 = pos - newChars(str2, str1, ',');
            if (pos2 >= 0) {
                setCaretPosition(pos2);
            } else setCaretPosition(0);
    public void focusGainedEvent(FocusEvent evt) {
        if (value == 0) {
            setCaretPosition(0);
    public void focusLostEvent(FocusEvent evt) {
        setText(doubleToStr(value, false));
    public double getValue() {
        return value;
    public void setValue(double val) {
       value = val;
}

I've corrected it and i think it's working pefectly, please give a try :-)
package sgpmde.forms.components;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.JTextField;
* @author jevb
public class JNumberField extends JTextField {
    private double value = 0;
    private NumberFormat nf = NumberFormat.getCurrencyInstance();
    private boolean dot = true;
     * General Constructor - add event listeners
    public JNumberField() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent evt) {
                keyTypedEvent(evt);
        this.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent evt) {
                focusGainedEvent(evt);
            @Override
            public void focusLost(FocusEvent evt) {
                focusLostEvent(evt);
        setText(doubleToStr(value, false));
    private double strToDouble(String str) {
        if (str.isEmpty()) {
            return 0.00;
        } else return Double.valueOf(str.replaceAll(",", ""));
    private String doubleToStr(double val, boolean evalDot) {
        StringBuilder num = new StringBuilder(nf.format(val));
        num.deleteCharAt(0);
        if (!getText().contains(".") && evalDot && value != 0) {
            num.delete(num.length() - 3, num.length());
        return num.toString();
    private int count(String str, char chr) {
        int c = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == chr) c++;
        return c;
    private int newChars(String str1, String str2, char chr) {
        int n = count(str2, chr) - count(str1, chr);
        if (n < 0) {
            return 0;
        } else return n;
    private void insert(char chr) {
        StringBuilder num = new StringBuilder();
        if (value > 0) {
            num.append(getText());
        } else {
            setCaretPosition(0);
            dot = true;
        num.insert(getCaretPosition(), chr);
        value = strToDouble(num.toString());
    private void delete() {
        StringBuilder num = new StringBuilder();
        if (getText().isEmpty()) {
            value = 0;
        } else {
            num.append(getText());   
            value = strToDouble(num.toString());
    private void keyTypedEvent(KeyEvent evt) {
        char chr = evt.getKeyChar();
        evt.setKeyChar((char) 0);
        if (((chr >= '0' && chr <= '9') || (chr == '.')) && (getCaretPosition() != getText().length() || !dot)) {
            dot = true;
            int pos = getCaretPosition();
            if (chr == '.') {
                if (getText().contains(".") && getText().charAt(pos) == '.') {
                    setCaretPosition(pos + 1);
                    chr = 0;
                } else if (getText().contains(".")) chr = 0;
            if (chr != 0) {
            insert(chr);
            String str1 = getText();
            String str2 = doubleToStr(value, false);
            setText(str2);
            setCaretPosition(pos + newChars(str1, str2, ',') + 1);
        if (chr == KeyEvent.VK_BACK_SPACE) {
            int pos = getCaretPosition();
            delete();
            String str1 = getText();
            String str2 = doubleToStr(value, true);
            setText(str2);
            int pos2 = pos - newChars(str2, str1, ',');
            if (!getText().contains(".")) {
                if (dot) pos2++;
                dot = false;
            if (pos2 >= 0) {
                setCaretPosition(pos2);
            } else setCaretPosition(0);
    public void focusGainedEvent(FocusEvent evt) {
        if (value == 0) {
            setCaretPosition(0);
    public void focusLostEvent(FocusEvent evt) {
        setText(doubleToStr(value, false));
    public double getValue() {
        return value;
    public void setValue(double value) {
       this.value = value;
       setText(doubleToStr(value, false));
}

Similar Messages

  • Customer Exit for Number of Days from 1 st Apr to last date of Month Enter

    Hello BI Experts,
    I have a requirement to count the number of days from 1 st April of current year to the last date of month entered.
    For example : The use will enter say July 2010 or 003.2010  (as Fiscal Year Variant is V3 ).
    Today is 14 July ...So we have to first find out the end date of the July month ie 31 st July
    Then go to 1 st April 2010.
    Now calculate the Number of days between 1 st April to 31 st July 2010.
    I consider I have to create two Customer Exit variable
    as below
    1 st customer exit Bex variable  say  ZLY_MTH  ( Last day of Month Entered)
      and i_step = 1
    2 nd Customer Exit BEx Formula variable say ZF_NUMDAYS ( Number of days between two dates)
    i_step =1 .
    Please provide me the logic for the above two.
    Thanks in Advance.
    Regards,
    Amol Kulkarni

    PSUDEO CODE:
    1. Initially LOOP AT I_T_VAR_RANGE INTO LOC_VAR_RANGE WHERE VNAM = 'ZMONTH'.
    2. Get the Month input using VAR_MONTH2 = LOC_VAR_RANGE-LOW+4(2)
    3. Now calculate Month+1: VAR_MONTH2 = VAR_MONTH2 + 1 (Refer **)
    4. Now calculate the Current Year: VAR_YEAR = LOC_VAR_RANGE-LOW+0(4).
    5. Get the 1st Day of the Month (VAR_MONTH2):  CONCATENATE '01' '/' VAR_MONTH2 '/' VAR_YEAR INTO L_S_RANGE-LOW.
    6. SUBRACT 1 (0DATE) from this DATE (This will give the logic for last day of the current month)
    Insert this code also for using the date conversions
            CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
              EXPORTING
                INPUT  = VAR_MONTH2
              IMPORTING
                OUTPUT = VAR_MONTH2.
    Pls. check out this logic. Guess it would solve your need.
    Thanks,
    Arun Bala

  • I am trying to understand the licensing procedures for using tabKiller for 3.5.7 firefox. Who should I contact for this? I do not see any customer service phone number for Firefox

    I am trying to understand the licensing procedures for using tabKiller for 3.5.7 firefox. Who should I contact for this? I do not have the customer service phone number for Firefox

    Tab Killer is not created by Mozilla, it is created by a private individual who has made it available at no cost for other people to use.

  • How to copy Customer Sales Order number to Purchase Order for 3rd party sal

    Hi experts,
    We are doing third party sales. So once we create Customer Sales Orders manually via VA01, users also manually create Purchase Req for it.
    We do not automatically create PR from Sales Order, as this is not my clients requirement. So we don't use item category group BANS in the material master.
    In the item level in the PR under the Contact Person tab, the creation indicator shows "V Sales & distribution document". Once PR is created this updates the PR number under the item level Schedule lines in the Sales Order.
    After PR creation, we run a job to create PO's.
    But the new requirement from the client is to automate this PO creation thru EDI.
    Our SAP is 4.6C & the Idoc type we use is ORDERS05 & Message Type is ORDERS. We are using EDIFACT std.
    Once I get the idoc xml file for this PO, I find that my Customer PO number (from the Sales Order) & also the Customer Sales Order number is not copying to the xml output.
    Please advise what needs to be done inorder to have it.
    This will be great help & I will reward for the answers !
    Rgds,
    Pri

    Tables are related.
    MATNR
    WERKS
    MBDAT
    LGORT
    CHARG
    etc fields are common in both VBBS and VBBE.
    May be you can generate a condition a fetch data using this.
    I hope it helps.
    thanks

  • Query for Customer site Phone number and Fax number  in Oracle Apps

    Dear All,
    Can anyone guide me how to write qurey for Customer site phone number and Fax number for Acive customers.
    Thanks in advance.
    Best Regards
    NRC

    Hi Team,
    This is a shipping report in header level we have the customer information with site address. The requirement is along with site address we need to show the phone number and Fax number .For this we need to write the formula column.Thes are the comes through HZ parties only. I have no idea how to achieve this.
    Best Regards
    NRC

  • Where to maintain TAN number in customer master for India

    Where to maintain TAN(Tax Deduction and Collection Account Number number) in customer master for India ?

    Hello Rohit,
    Where to maintain TAN(Tax Deduction and Collection Account Number number) in customer master for India ?
    Go to the T-code XD01 or XD02 and you can enter the TAN details in the CIN Details Tab of the Customer Master record.
    Or use the transaction J1ID-->Customer Excise details.
    Regards,
    Sarthak

  • OMG...does anyone have a phone number that I can talk to anyone in customer service for an itune dispute on an iphone?

    OMG...does anyone have a phone number that I can talk to anyone in customer service for an itune dispute on an iphone?

    There is no telephone support for itunes. 
    Use the contact link provided in the previous post.

  • How to edit/delete a custom label for a tel number for example in contacts?

    How to edit/delete a custom label for a tel number for example in contacts?

    Alfre311 wrote:
    I've been trying to find a way to do this since I updated to IOS 7, and I've just found the solution/explanation, even tho is a bit heavy to carry out.
    IOS 6 creates custom labels and save them giving you the option to delete them.
    IOS 7 creates custom labels but don't save them, so there is no need to have the option to delete them.
    But here comes the problem, if you have some custom labes saved in you Iphone / Ipad with IOS 6 and you update it to IOS 7, the device will keep those labels saved, but you wont be able to delete them.
    I realized this by going to contacts on Icloud. There those labels that I had on my devices weren't there. So simply restoring your device and configuring it as a new one to later sync your Icloud Contacts, will solve the problem.
    I know this post is old, but I might just try this with iOS 8. I have outdated custom labels that annoy me, because I still seem them in the list as options. If I get desperate enough, I may try your solution.

  • Anyone know the customer support phone number for eastern standard time

    anyone know the customer support phone number for eastern standard time?

    telephone http://helpx.adobe.com/x-productkb/global/phone-support-orders.html

  • How to create custom infotype for training and event management

    hai freinds can any one tell me how to create custom infotype for training and event managment with following fields
    PS No – PA0000-> PERNR
    Name   - PA0001 -> ENAME
    IS PS.No. – PA0001-> PS no. of Immediate Superior
    IS name PA0001 -> ENAME
    thanx in advance
    afzal

    Hi,
    Your question is not clear for me. Since it is a TEM infotype, it could be a PD infotype.
    If you wish to create a PD infotype, use transaction PPCI to create the infotype.
    But before that you need to create a structure HRInnnn (where nnnn is the infotype number) with all the fields relevant for the infotype.
    If you wish to create a PA infotype, use transaction PM01 to create the infotype.
    But before that you may be required to create a strcuture PSnnnn  (where nnnn is the infotype number) with all the fields relevant for the infotype.
    Regards,
    Srini

  • Replicating Custom Fields for Products in CRM  from ECC

    Hi All,
    I am having difficulty in replicating SAP standard field values from ECC to custom fields for products in CRM. This is what i did:
    1. I created a new settype(ZMASTER_INFO) with a single attribute(ZIND_STD) and added
        this new settype to MAT_HAWA. (As all our materials fall under this material type).
    2. I am looking to map SAP standard field from ECC to this custom field of mine.
        I wrote the code in CRM BADI 
        'ZPRODUCT_CUSTOMER2->MAP_R3_TO_CRM_MATERIAL' with the following code:
    DATA: ls_ZMASTER_INFO TYPE ZMASTER_INFO_maintain.
    DATA: ls_category_bdoc       TYPE COMT_PROD_CAT_REL_MAINTAIN,
          ls_category            TYPE COMT_PROD_CAT_REL,
          lt_categories          TYPE COMT_PROD_CAT_REL_TAB,
          ls_settype             TYPE COMT_settype_ext,
          ls_cat_settype_rel     TYPE COMT_CAT_FRAG_REL,
          lt_cat_settype_rel     TYPE COMT_CAT_FRAG_REL_TAB,
          lt_cat_settype_rel_all TYPE COMT_CAT_FRAG_REL_TAB.
    LOOP AT lt_cat_settype_rel_all INTO ls_cat_settype_rel.
          CALL FUNCTION 'COM_SETTYPE_READ_SINGLE'
            EXPORTING
              IV_SETTYPE_GUID         = ls_cat_settype_rel-frgtype_guid
            IMPORTING
              ES_SETTYPE              = ls_settype
           EXCEPTIONS
             NOT_FOUND               = 1
             NO_IMPORT_VALUES        = 2
             NO_TEXT_FOUND           = 3 .
          IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
      CASE ls_settype-frgtype_id.
          WHEN 'ZMASTER_INFO'.
          ls_ZMASTER_INFO-relation-owner = 'X'.
          ls_ZMASTER_INFO-relation-logsys = cs_product_bdoc-header-com_product-logsys.
          ls_ZMASTER_INFO-data-ZZ0010 = is_mara-STD_DESCR.
          ls_ZMASTER_INFO-DATA_X-ZZ0010 = 'X'.
          APPEND ls_ZMASTER_INFO TO cs_product_bdoc-data-ZMASTER_INFO.
          APPEND ls_settype-FRGTYPE_GUID TO cs_product_bdoc-data-MNT_SETTYPE.
       ENDCASE.
    ENDLOOP.
    Since in ECC i am not having any custom fields i did not write any code in ECC for TPS34 and TBE24. I just wrote this BADI in CRM and using the field S_MARA-STD_DESCR.
    I am not sure if i need to write the code in ECC. COUld anyone please confirm if i need the code in ECC?
    Also in the CRM BADI, lt_cat_settype_rel_all is EMPTY. Not sure how this gets its value.
    Could anyone please suggest if i am missing anything here? Any help is appreciated.
    Thanks,
    Karuna.

    Hi Karuna,
    One more solution is to change the BDoc data content before it hit the Database.
    this can be done in badi: Data_Exchange_badi (if u dont find this try with following search string: xchange)
    In the above mention badi you will find a method which is used to populated the contend jst after bdoc in CRM is being populated by R/3 data.
    Best Regards,
    Pratik Patel
    <b>Reward with Points!</b>

  • Wrong Calculation of Custom Duty for Import PO

    Dear Experts,
    We have made one PO for Import and after that we have made custom duty for the same PO and then we have captured the excise invoice through J1iex T.code. But when we have posted the MIGO it is calculating wrong custom duty that particular G/l.  In this particular Vendor all other PO is ok but in one PO it is creating a problem
    Regards,
    Pankaj Rana

    Hello Pankaj,
    I believe our MM colleagues could better help you (or consultant from component XX-CSC-IN-MM), but I'll try to as well.
    These notes seem promising
    1319544 Validation for commercial invoice MIGO ref note : 1303077
    1303077 Validation for commercial invoice entered in MIGO for import
    1368698 No validation for reversed Commercial Invoice in J1IEX
    1345945 MIGO doesn't consider Year to pick Commercial Invoice Number
    Hope this helps somehow.

  • Customer exit for Batch management

    Hi experts,
    I'm using customer exit for batch management for internal number assignment.
    I need the Batch number as i mentioned below 
    DDMMYYB01
    DD-Date
    MM-Month
    YY-Year
    B-Block
    01-Number
    For this i need to give logic. How to give i'm not getting. This batch number creation will come at the time of GR.
    Anybody help me?
    Naren

    Hi
    Please use the user exit SAPLV01Z as I mentioned in your other thread, please go to SMOD to read its documentstion.
    In SMOD, select the 'Documentation' and click 'Display', this will show the overview documentation.
    Select the 'Componnet', then ciick the 'Display'. select each component and click 'Documentation Ctrl+F4) this will show the detailed documentation of them.
    Best Regards.
    Leon.

  • Customized report for cost centers by different cost centers

    Hi All,
    Customized report for cost centers by different cost centers:
    I need to build a customised report with the following format:
    Cost element columns | Cost center 1 | cost center 2 | cost center 3, etc -> dynamic cost center columns
    CE 1 .............................. amount xxx  |  . amount xxx | ..  amount xxx
    CE 2 .............................. amount xxx  |  . amount xxx | ..  amount xxx
    CE 3 .............................. amount xxx  |  . amount xxx | ..  amount xxx
    CE 3 .............................. amount xxx  |  . amount xxx | ..  amount xxx
    User selection screen:
    Controlling are:
    Fiscal Year:
    From period to period:
    cost center group ... <range of CC group> or
    cost center value ... <range of CC value>
    Questions:
    From the above selection screens, I need to pull out all the data stored in the table: COEP
    But, the problem is that inside this table, there is no cost center or cost center group stored; and therefore the program should be smart enough to pull out all the documents from the table: COEP and then make sure that the document / list of documents that pull out should belongs to the cost center or cost center group, as well as date range.
    KIndly advise how functional description/design should be built in order ABAPer can understand the requirement?
    What should be the tables to refer in order meet the requirement.
    Similar Standard SAP cost center report should be S_ALR_87013611 - Cost Centers: Actual/Plan/Variance, but this report read from many tables.

    Hi,
    Please find the logic below & try it at your system-
    Here cost center group is not possible (also i not checked it so do it on your own simultaneously i am trying the same).
    Use Table BSEG-> in bseg give the cost center-> with the help of cost center find the account number (field HKONT)-> take this GL account number & got to table COEP-> in this give the GL account number at field 'offsetting account' (field GKONT) & you will get the line item.
    Try it & let me know if you have any question.
    Thanks

  • How to add custom action for Publishing Tab on Pages?

    I am able to add a custom action for libraries tab on document library , but i am unable to add it on Publishing tab on Pages.
    Below is the code , what i am trying.
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
    Id="Ribbon.PublishTab.Publishing.CheckLinkedPageItems"
    Location="CommandUI.Ribbon"
    RegistrationType="List"
    RegistrationId="850"
    Sequence="40"
    Title="Move Documents">
    <CommandUIExtension>
    <CommandUIDefinitions>
    <CommandUIDefinition Location="Ribbon.PublishTab.Publishing.Controls._children">
    <Button
    Id="Ribbon.PublishTab.Publishing.CheckLinkedPageItemsButton"
    Alt="Check Linked Page Assets"
    Sequence="40"
    Command="CheckLinkedPageItems"
    Image32by32="/_layouts/images/centraladmin_systemsettings_email_32x32.png"
    LabelText="Check Assets"
    TemplateAlias="o1"
    ToolTipTitle="Check Linked Page Assets"
    ToolTipDescription="Checks each image, document and page linked to from this page and verified if the asset is both working (not a broken link) and published. You may also use that page to publish all unpublished assets at once."
    />
    </CommandUIDefinition>
    </CommandUIDefinitions>
    <CommandUIHandlers>
    <CommandUIHandler Command="CheckLinkedPageItems" CommandAction="javascript:alert('button clicked!);" />
    </CommandUIHandlers>
    </CommandUIExtension>
    </CustomAction>
    </Elements>
    any thoughts?

    Hi,
    Check the secquence number . I don't see any issue in your code. Try with different sequence numbers.
    Did you find this Helpful? Please Mark it So! Thank you. Sachin Kumar

Maybe you are looking for