In need of customized JTextField

I need to create a custom textfield, and the formatter won't cut it. I need to have formatting applied real time, with a variable number of characters. The ATM might be a good example, where you enter numbers and the display field fills in from left to right, with the decimal point and dollar sign always being in the correct location, the entry of a decimal point is optional, and comas appear as necessary as the number of digits to the left of the decimal point increases.
I have similar needs for percentage, and a few other value types. Currently I've extended PlainDocument and have it working, but I'm far from happy with the results, and wasn't able to make it abstract enough to be easily usable for slightly different formats.
Has anybody seen a component like this floating around? I would hate to recreate what somebody else has already done, particularly of the later effort has resulted in a better solution.
Thanks,
-Dave

does it have to be a textField?Yes - the users are quite adamant and and specific regarding the requirements for this field.
At first glance, your single replaceAll statement looks much simpler than what I've worked out. I think that some of the extra leg work I'm doing may not be necessary, but I do need to figure out where to insert numbers (in case of entry mid field), where deletions occur, where to place the character after updates, etc.
I'm posted what I've come up with below. I'm not happy with it - am still looking for the right solution, which I must have glossed right over.
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class TestTextField {
     public static void main(String[] args) {
          JTextField myTextField = new JTextField();
          myTextField.setHorizontalAlignment(JTextField.RIGHT);
          myTextField.setDocument(new UpperCaseDocument(myTextField));
          JFrame frame = new JFrame();
          frame.getContentPane().setLayout(new GridLayout(3, 1));
          frame.getContentPane().add(myTextField);
          frame.pack();
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setVisible(true);
class UpperCaseDocument extends PlainDocument{
     StringBuffer contents;
     JTextField tf;
     public UpperCaseDocument(JTextField tf) {
          this.tf = tf;
          contents = new StringBuffer();
          contents.append("000");
          try {
               super.insertString(0, NumberFormat.getCurrencyInstance().format(0),
                         null);
          } catch (BadLocationException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
     public void insertString(int offs, String str, AttributeSet a)
               throws BadLocationException {
          if (str == null) {
               return;
          boolean allNumbers = isNumeric(str);
          if (allNumbers) {
               int offset = calcOffset(offs);
               contents.insert(offset, str);
               padContents();
               set(a);
               int caret = calcCaret(offset + str.length());
               System.out.println("C: " + caret);
               tf.setCaretPosition(caret);
          } else {
               Toolkit.getDefaultToolkit().beep();
     public void remove(int offs, int len) throws BadLocationException {
          super.remove(offs, len);
          String s = getText(0, getLength());
          s = replace(s, "$", "", -1);
          s = replace(s, ",", "", -1);
          s = replace(s, ".", "", -1);
          contents.replace(0, contents.length(), s);
          set(null);
          padContents();
          tf.setCaretPosition(offs);
     private void set(AttributeSet a) {
          try {
               String s1 = contents.substring(0, contents.length() - 2);
               String s2 = contents.substring(contents.length() - 2);
               String amount = s1 + "." + s2;
               double d = Double.parseDouble(amount);
               String curr = NumberFormat.getCurrencyInstance().format(d);
               super.remove(0, getLength());
               super.insertString(0, curr, a);
          } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
     public static String replace(String text, String repl, String with, int max) {
          if (text == null || with == null || max == 0) {
               return text;
          StringBuffer buf = new StringBuffer(text.length());
          int start = 0, end = 0;
          while ((end = text.indexOf(repl, start)) != -1) {
               buf.append(text.substring(start, end)).append(with);
               start = end + repl.length();
               if (--max == 0) {
                    break;
          buf.append(text.substring(start));
          return buf.toString();
     private int calcOffset(int offset) {
          // Take 1 off the top to accomodate for dollar sign
          if (offset > 0) {
               offset--;
          int numCommas = (contents.length() - 2) / 3;
          if (numCommas > 0 && (contents.length() - 2) % 3 == 0) {
               numCommas--;
          int prefix = (contents.length() - 2) % 3;
          if (prefix == 0) {
               prefix = 3;
          int commaShift = 0;
          for (int i = numCommas; i > 0; i--) {
               if (offset > prefix) {
                    commaShift++;
                    prefix += 4;
               } else {
                    break;
          offset -= commaShift;
          int secret = contents.length() + 1 - 2;
          if (offset > secret) {
               offset--;
          return offset;
     private int calcCaret(int offset) {
          if (offset > contents.length()) {
               System.out.println("oops");
               return getLength();
          // Take 1 off the top to accomodate for dollar sign
          if (offset > 0) {
               offset++;
          int numCommas = (contents.length() - 2) / 3;
          if (numCommas > 0 && (contents.length() - 2) % 3 == 0) {
               numCommas--;
          int prefix = (contents.length() - 2) % 3;
          if (prefix == 0) {
               prefix = 3;
          int commaShift = 0;
          for (int i = numCommas; i > 0; i--) {
               if (offset > prefix) {
                    commaShift++;
                    prefix += 3;
               } else {
                    break;
          offset += commaShift;
          int secret = getLength() - 2;
          if (offset > secret) {
               offset++;
          return offset;
     private void padContents() {
          if (contents.length() < 3) {
               int pading = 3 - contents.length();
               for (int i = 0; i < pading; i++) {
                    contents.insert(0, "0");
          } else {
               int excess = contents.length() - 3;
               for (int i = 0; i < excess; i++) {
                    if (contents.charAt(0) == '0') {
                         contents.deleteCharAt(0);
                    } else {
                         break;
     public static boolean isNumeric(String str) {
          if (str == null) {
               return false;
          int sz = str.length();
          for (int i = 0; i < sz; i++) {
               if (Character.isDigit(str.charAt(i)) == false) {
                    return false;
          return true;
}

Similar Messages

  • Strange behaviour whit custom JTextField and JToolTip

    Hello everyone. I hope I'm writing in the right section and sorry if I did not search for this issue but I really don't know which keywords I should use.
    I'm using NetBeans 6.1 on WinXP and JDK 1.6.0_07, I have a custom JTextField with regex validation: when you type something that don't mach regex it shows a JToolTip. This JToolTip should disappear when the text typed is finally correct, or when the textfield loses focus (see code below).
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import javax.swing.JToolTip;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    public class MyJTextField extends javax.swing.JTextField implements FormComponent
    private static Popup popUpToolTip;
    private static PopupFactory popUpFactory = PopupFactory.getSharedInstance();
    private boolean isValidated = false;
    private String regEx = "a regex";
    public MyJTextField()
    this.addKeyListener(new java.awt.event.KeyAdapter()
    public void keyReleased(java.awt.event.KeyEvent evt)
    if(evt.getKeyCode()!=java.awt.event.KeyEvent.VK_ENTER)
    validateComponent();
    else if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
    if(isValidated)
    ((Component)evt.getSource()).transferFocus();
    this.addFocusListener(new java.awt.event.FocusAdapter()
    public void focusLost(java.awt.event.FocusEvent evt)
    if(popUpToolTip!=null){popUpToolTip.hide();}
    public void validateComponent()
    if(text.matches(regex))
    isValidated = true;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    else
    isValidated = false;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    String error = "C'&egrave; un errore nella validazione di questo campo";
    JToolTip toolTip = createToolTip();
    toolTip.setTipText(error);
    popUpToolTip = null;
    popUpToolTip = popUpFactory.getPopup(
    this,
    toolTip,
    getLocationOnScreen().x,
    getLocationOnScreen().y - this.getPreferredSize().height -1
    popUpToolTip.show();
    }(I've cut it a bit, here's only the lines that involve JToolTip use)
    I have many of them in a form, and when the first tooltip appears (on the first textfield I type in) it never disappears, while nex textfields work just fine.It seems the first tooltip appearing can't be overwritten or something similar. If I use this same component on any other NetBeans project, everithing works without issues.
    I have some other custom components working the same way (JComboBox, JXDatePicker), and they had this "not disappearing tooltip" issue since I changed this
    popUpToolTip = popUpFactory.getPopup(this, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    whit this
    popUpToolTip = popUpFactory.getPopup(null, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    but if I try it on the JTextField all textfield's tooltips stay stuck there, not only the first one appeared (while other components still works fine).
    This thing is really driving me crazy. Someone has an hint (or a link to another thread) which could explain this strange behaviour?
    Thanks in advance.

    BoBear2681 wrote:
    Note that an SSCCE wouldn't require you to post any proprietary code.Hmmm... well, I'll try again to reproduce the issue and post an SSCCE.
    BoBear2681 wrote:
    That probably indicates that the problem is somewhere other than where you're currently looking.Yes, I suppose so. Maybe it's some interference between all the custom components I created, or maybe something else that apparently doesn't conern at all. If I cannot reproduce it in an SSCCE and I'll figure out what's the cause of this mess I'll post it here for future knowledge.
    Many thanks for your advices. :)

  • Trying to cancel my membership..need a customer service phone number

    trying to cancel my membership..need a customer service phone number

    Hi NortherLights56,
    Please see the link below to cancel membership:
    Cancel your membership or subscription | Creative Cloud
    You may see the below mentioned link to contact Customer/Chat support:
    http://www.adobe.com/support/download-install/supportinfo/
    Let us know if this helps,
    Regards
    Gurleen Kaur

  • Why do u need a custom structure for creating a custom bapi

    Hi ,
    why do u need a custom structure for creating a custom bapi.

    Hi,
        Once any Bapi realeased the structures it is using freezed to this bapi, the structure becomes specific to this Bapi, we can not make any changes over there. That is why we need custom structure for creating a custom bapi.

  • Need a custom exentsion built for me.

    I will soon be needing a custom extension built for a
    software program. Where to I post a job such as this? Is this the
    right forum? Or is there another forum that specifically hooks up
    developers with companies that need a custom extension?
    Thanks!
    eCat

    Contact us with your specifications etc.. and we will evalute
    the project.
    http://www.fourlevel.com/support.htm
    Regards,
    ..Trent Pastrana
    www.fourlevel.com
    "mlstover" <[email protected]> wrote in
    message
    news:eh6976$rua$[email protected]..
    >I will soon be needing a custom extension built for a
    software program.
    >Where
    > to I post a job such as this? Is this the right forum?
    Or is there another
    > forum that specifically hooks up developers with
    companies that need a
    > custom
    > extension?
    >
    > Thanks!
    > eCat
    >

  • Need show Customized heading on Bex analyzer

    Hi All,
    I need show Customized heading on Bex analyzer or report selections. ex: i selected company code
    1000 to 4000.  It has to show as heading.
    I know this is possible only through workbook.
    May i know the steps. How to do it.
    Thanks,
    KN

    you have create a text variable with replace ment path on com code

  • I need Skype Customer Service and there is none. I...

    I am having issues with my Skype account(s).
    I need to speak to someone in customer service. This is not a do it yourself tech issue.
    There is no customer service.
    Only this forum.
    I'm so frustrated with Skype right now.
    For having **bleep**ed up programming which caused the glitches in the first place.
    And for failing to have an adequate remedy.

    here are possible more detailed instructions;
    http://community.skype.com/t5/General-Discussion/How-to-Contact-Skype-Customer-Service/m-p/431911
    IF YOU FOUND OUR POST USEFUL THEN PLEASE GIVE "KUDOS". IF IT HELPED TO FIX YOUR ISSUE PLEASE MARK IT AS A "SOLUTION" TO HELP OTHERS. THANKS!
    ALTERNATIVE SKYPE DOWNLOAD LINKS | HOW TO RECORD SKYPE VIDEO CALLS | HOW TO HANDLE SUSPICIOS CALLS AND MESSAGES

  • Function module needed for customer exit variable need to use in Bex report

    Hi Experts,
    I have a requirement where i need to get Cummulative result between two interval periods.
    If user gives single mandatory input value - 002-2009
    for one Scenario:-
    Project start Date   untill Pervious year i.e  December 2008
    Where project start date will get from one of the field in my BW CUBE
    can anyone help for the customer exit function code for this scenario. As i am into BI i dont have idea in ABAP.
    Please help sample cod for this .
    Thanks,
    Anil.

    I had created one customer exit which had fullfill my requirement.

  • Urgent help needed -in customizing an OAF page --adding new button?

    Hi,
    We are currently implementing an OAF based oracle application.One of the requirements that the customer has is to display an additional button on the page button bar available out of box in an OAF page. This button needs to be enabled/disabled based on certain conditions. Also when the button is pressed a pl/sql api needs to be invoked. I know through personalization a new button can be created in the page button bar. But how do we handle the logic behind the button? Can we extend the page level controller?Will this survive future upgrades? If not then what is the alternative?
    Please help!
    Thanks!

    You can follow the thread Calling PL/SQL Procedure for pl/sql call from controller example.
    --Shiv                                                                                                                                                                                                                                                                                   

  • Help needed regarding custom reports

    hello,
    I am using EM 10.2.0.2 on windows 32-bit.
    All EM components are installed on a single machine.
    Have installed AGENT 10.1.0.5 for managing targets which are on LINUX 2.1
    Please help me in getting the solution for the following queries:
    (a)I need to create a custom report regarding the CAPACITY MANAGEMENT .
    (b)I have some UDM defined but I am not able to use these UDM while creating custom report.
    (c)Also is there any possibility that we can use views other than REPOSITORY VIEWS. What I meant was : instead of using REPOSITORY VIEWS can we use the tables of the target instances.
    Thanks in advance.

    You might want to try posting your question to the Grid Control Forum.
    Enterprise Manager

  • Help needed in customer exit code to exclude a value

    Hi Gurus,
    I need to use a Customer Exit Variable to read the values for a characteristic. Based on one indicator I have to include or exclude a value. I am trying to use the code as below. But, it is saying "AError for variable  in customer enhancement ...".
    Code
    the variable is a multiple single values customer exit variable
             zl_s_range-low = z_placc.
             CLEAR zl_s_range-high.
             if z_pl_ind = '1'.
               zl_s_range-sign = 'I'.
             elseif z_pl_ind = '2'.
               zl_s_range-sign = 'E'.
             endif.
              zl_s_range-opt = 'EQ'.
             APPEND zl_s_range TO e_t_range.
    Please help me to solve the issue,
    Thanks in advance,
    Regards,
    aarthi

    Hi Uday,
    Thanks for your response.
    Below is the complete code.
    WHEN 'ZV_CSS11'.
    IF I_STEP = 1.      "Before Pop-up
       select * into table i_tp_tab_pl from /BIC/QZ_TP_PLAC
        where /BIC/Z_TP_PLAC = '11' and
            DATEFROM <= sy-datum and DATETO >= sy-datum.
    if sy-subrc = 0.
         LOOP AT i_tp_tab_pl.
             clear zl_s_range.
             z_placc = i_tp_tab_pl-/BIC/Z_PLACC.
             z_pl_ind = i_tp_tab_pl-/BIC/Z_PGLA_IND.
             zl_s_range-low = z_placc.
             if z_pl_ind = '1'.
               zl_s_range-sign = 'I'.
             else.
               zl_s_range-sign = 'E'.
             endif.
              zl_s_range-opt = 'EQ'.
             APPEND zl_s_range TO e_t_range.
             clear z_placc.
             clear z_pl_ind.
          ENDLOOP.
    endif.
    endif.
    Thanks in advance,
    Regards,
    aarthi

  • Need my custom webauth page displayed with HTTP instead of HTTPS

    I have a custom webauth page installed that I am using with web passthrough authentication on my WLC2006 in order to put up a acceptable use policy page.
    The WLC uses HTTPS to display this which causes a security certificate warning to appear if I go with the WLC's own self-signed certificate. Is there a way I can get the WLC to use plain HTTP to display this page instead so I can eliminate the warning?
    I have already tried installing a trusted 3rd party certificate on the WLC, but I have this very strange problem where mucking with the WLC's web authentication certificate in any manner causes all network activity on the WLC to break except for CDP and ARP, essentially leaving the WLC dead. Three weeks of troubleshooting with Cisco TAC has yielded no progress on that front so now I am trying to bypass the need for a security certificate altogether since I really don't need to encrypt my acceptable use policy page.

    The documentation doesn't provide very clear direction, does it?
    To download the WLC's default webauth page, browse to the controller's Security > Web Login Page. Make sure the web authentication type is Internal (Default). Hit the Preview button. Then use your browser's File > Save As... menu item to save the HTML into a file. Edit this to your liking and bundle it and any graphics images up into a TAR archive, then upload via the controller's COMMAND page.

  • The Nordins - Options for the next time you need a customer!

    The headline is from an email we received: "Verizon - Options for the next time you need customer service!"  Well, we changed it, just slightly.   Well, on 6/20/2013 we had the TV down; it was said to be a piece of video equipment that went down.  We could not get anything on the TV until next day.  The sad part is that we were watching the Heat-Spurs game and it quit just 1min-36sec. prior to the end of the game.  Then, we could not watch our daily Netflix show we watch every evening before going to bed.  So in calling twice, we found out about the video equipment problem.  But typically Verizon, they replaced the equipment and thought nothing about the customer that actually lost the reception!!  How about crediting us for the time "off the air".  You can't have the cake and eat it too.  Then, Verizon sends us emails about the bill, customer service, etc. but there is no way for us to email them back!!  Why do they think my time is less valuable then theirs; having to call their customer service and to wait a long time for answer by someone in "God knows where country".  What does that tell you about the customer service commitment!  It's like, yeah you are one of the slob users that keep paying the bills for lousy service.   Perhaps it's time for all of us to switch off our TV's for one or two days a week and not pay them for "our time off the grid".  Having some couple of thousand TV's off twice a week may shake them up a bit.   So here is my idea.  Establish an email address where we can reach anyone in customer service directly, in our own state, not somewhere 1000 and more miles away.  Additionally, if something is down, does not matter what time of the day, stand up for it and give the customer their credit due.  Thanks for reading

    It all depends how you use it.
    Once the initial break in period is over, like the first year, it should run just fine as long as you don't abuse it, don't let it overheat, keep the dust out etc.
    Do get the AppleCare as it's very expensive to repair a Mac.
    Some tips:
    1: Avoid using the built in keyboard and trackpad as much as possible. I know what's the use, but it's these too area's, the USB ports and the Superdrive that experience the most wear and tear.
    2: If you do use the built in keyboard, take off your watch and jewelry, it scratches. mars, reacts with the case and discolors it.
    3: The keybord is a bit weak compared to regular PC desktop keyboards, so use a wireless one, but have a wired one around for emergencies. The keyboard collects dirt, grime, hair, dust etc, underneath, you might want to have a light cover over the keys but still let air get underneath.
    4: Be gentle with the audio ports and the Superdrive, don't use your computer for watching DVD's. The Superdrive is important for recovering the machine with the installer disk which also must be well taken care of.
    5: A GOOD case, like a MacTruck or a padded one will absorb the shocks if dropped while transporting.
    6: The biggest concern is other people, they just don't handle things with care because it's not theirs and they are ignorant or even spiteful of the money you spent to have a quality machine.
    7: Clone your boot drive to a external regularly, in fact have two, one staggered back in time a few weeks, it's hold option bootable in case your hard drive dies. Free cloning software like Carbon Copy Cloner or the commercial version Superduper does the job well.

  • Need to customized report in solution manager but duno which table to pull

    Dear Gurus,
    I need to create a customized report in solution manager to get the following fields:
    1) Message number
    2) Transport number link to the message number
    3) Target client the transport go to
    4) Date/Time of status change to "Consolidate"
    5) Date/Time of transport imported
    6) Date/Time of Email Sent through message when requesting for transport
    Pls, help find the relation tables for the above objects, I'm a developer without any functional help and with no knowleadge of solution manager. Pls, help ASAP!
    Desperate,
    Belinda

    Hi Belinda,
    open the service message application in the Solman.
    Open a service message, focus the needed fields and press F1 for technical details. Try finding the tables by using the      where-used list.
    Cheers,
    André

  • Can we have approve/reject action button in email sent using SharePoint designer or do we need to custom code it?

    Hello,
    for particular item approval, when user receives an email, can email contain button of approve/reject or if user just replies to that mail using one word "Approve/Reject", so that item value should get updated in list and also get approved.
    Is it possible using SharePoint designer workflow or custom code workflow or Nintex workflow?
    Please guide.
    Thanking you in advance.
    Regards,
    Jayashri

    Follow these steps:
    You can create custom page with code to approve/reject item.
    Then you should pass item id (and other information if needed) in a query string.
    In a workflow you can generate a link to the created page and add it to email body.
    When a user will receive email, he/she will click on the button (link), then new tab with created page will be opened, where your custom code will approve an item.
    [custom.development]

Maybe you are looking for

  • Plz help me in this

    can anyone tell what will happen in production support  means what  the activities has to perform which type of errors will come. Thnks

  • Restricting FXS ports to internal calls only

    Hi, I have recently intalled Call Manager 8.5.1 with a H323 Gateway. On the gateway, I have a number of FXS ports for lobby phones. Is there a way I can restrict these phones to allow only internal calls only? Do I need to use COR lists like in Call

  • WebAS ABAP 6.40 Post install problem

    I am having a problem with the install of the ABAP component for Web AS 6.40.  I have used Sql Server 2000 (8) as the database on a windows Server 2003 operating system.  The system appears to have installed correctly (as far as I can tell). I am at

  • Regarding ALV selection screen

    hi all, my issue: i have an alv report which has almost 10 paramters based on which the internal table will be populated. the two parameters are mandatory .. 4 are select options and 4 are radiobuttons. i think this will lead to a lot of select queri

  • Clone users, multiple Macs

    I am starting a roll-out of 35 or so iMacs to relplace XP machines. I would like to limit user app's, and settings. If I use parental control, and customize the user can I save or export the setting so I can use the same setting etc. to the other mac