JTextField to remove characters automatically when overwritting selectedIterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loopRemove last character of a StringBuilder?Drag and Drop nodes in JTreeJtextField with data validation and BeansbindingHow to remove the last character from a string?Type mismatch in key from map: expected .. Text, received … LongWritableDrawing an image in JScrollPane within scaleAdd backspace to Documentfilterin java awt or swing, how can I arrange for keyboard input to go wherever the mouse is?why spill failure happens for Custom Data Type in Hadoop

Why do planes need a roll motion?

How can I receive packages while in France?

Commercial jet accompanied by small plane near Seattle

How do I address my Catering staff subordinate seen eating from a chafing dish before the customers?

Is it legal for private citizens to "impound" e-scooters?

Is dd if=/dev/urandom of=/dev/mem safe?

How can I stop myself from micromanaging other PCs' actions?

Unethical behavior : should I report it?

Piece-drop Mate #3

How much were the LMs maneuvered to their landing points?

Why isn't there a ";" after "do" in sh loops?

Examples of simultaneous independent breakthroughs

Problem in styling a monochrome plot

Request for a Latin phrase as motto "God is highest/supreme"

How to avoid unconsciously copying the style of my favorite writer?

How do campaign rallies gain candidates votes?

How do I stop my characters falling in love?

Did the IBM PC use the 8088's NMI line?

When going by a train from Paris to Düsseldorf (Thalys), can I hop off in Köln and then hop on again?

What is the difference between 1/3, 1/2, and full casters?

Can two figures have the same area, perimeter, and same number of segments have different shape?

Integral of the integral using NIntegrate

Is a fighting a fallen friend with the help of a redeemed villain story too much for one book

Character is called by their first initial. How do I write it?



JTextField to remove characters automatically when overwritting selected


Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loopRemove last character of a StringBuilder?Drag and Drop nodes in JTreeJtextField with data validation and BeansbindingHow to remove the last character from a string?Type mismatch in key from map: expected .. Text, received … LongWritableDrawing an image in JScrollPane within scaleAdd backspace to Documentfilterin java awt or swing, how can I arrange for keyboard input to go wherever the mouse is?why spill failure happens for Custom Data Type in Hadoop






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm working with Java and I have a JTextField which can only have 4 digits. I'm using a class that extends DocumentFilter to filter out any other character, and to limit the number of characters to 4.



The problem is that once I have 4 digits, if I select all of them and try to overwrite them by typing another digit it doesn't auto overwrite and does nothing, I have to explicitly type "Backspace" or "Delete" in my keyboard to remove the 4 digits and then (once the field is clear) I can type again.



How can I make the JTextField act as the rest of the operating system that once I have some text selected if I type a character it “removes all, then writes the character” (it substitutes the contents).



I have one aux class, JustLimitDigitFilter.java:



import javax.swing.text.DocumentFilter;
import javax.swing.text.BadLocationException;

import java.awt.Toolkit;

import javax.swing.text.AttributeSet;

public class JustLimitDigitFilter extends DocumentFilter

int limit;

public JustLimitDigitFilter(int limit)
this.limit = limit;


@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException

// if (text == null)
// return;
//
String str = text.replaceAll("\D", "");
if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
super.insertString(fb, offset, str, attr);
else
Toolkit.getDefaultToolkit().beep();




@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr)
throws BadLocationException

// if (text == null)
// return;
//
String str = text.replaceAll("\D", "");
if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
super.replace(fb, offset, length, str, attr);
else
Toolkit.getDefaultToolkit().beep();







And the main class, App.java:



import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;

public class App

private JFrame frame;
private JTextField textField;

/**
* Launch the application.
*/
public static void main(String[] args)
EventQueue.invokeLater(new Runnable()
public void run()
try
App window = new App();
window.frame.setVisible(true);
catch (Exception e)
e.printStackTrace();


);


/**
* Create the application.
*/
public App()
initialize();


/**
* Initialize the contents of the frame.
*/
private void initialize()
frame = new JFrame();
frame.setBounds(100, 100, 191, 96);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JPanel panel = new JPanel();
panel.setBounds(6, 6, 179, 62);
frame.getContentPane().add(panel);
panel.setLayout(null);

textField = new JTextField();
textField.setBounds(6, 6, 167, 26);
panel.add(textField);
textField.setColumns(10);

// without this code below this, the textfield is “normal” when
// something is selected if I write it overwrites the selection

AbstractDocument doc = (AbstractDocument) textField.getDocument();
doc.setDocumentFilter(new JustLimitDigitFilter(4));





Any suggestion is welcome since I'm new to this, apart from the doubt I explicitly have.










share|improve this question




























    0















    I'm working with Java and I have a JTextField which can only have 4 digits. I'm using a class that extends DocumentFilter to filter out any other character, and to limit the number of characters to 4.



    The problem is that once I have 4 digits, if I select all of them and try to overwrite them by typing another digit it doesn't auto overwrite and does nothing, I have to explicitly type "Backspace" or "Delete" in my keyboard to remove the 4 digits and then (once the field is clear) I can type again.



    How can I make the JTextField act as the rest of the operating system that once I have some text selected if I type a character it “removes all, then writes the character” (it substitutes the contents).



    I have one aux class, JustLimitDigitFilter.java:



    import javax.swing.text.DocumentFilter;
    import javax.swing.text.BadLocationException;

    import java.awt.Toolkit;

    import javax.swing.text.AttributeSet;

    public class JustLimitDigitFilter extends DocumentFilter

    int limit;

    public JustLimitDigitFilter(int limit)
    this.limit = limit;


    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException

    // if (text == null)
    // return;
    //
    String str = text.replaceAll("\D", "");
    if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
    super.insertString(fb, offset, str, attr);
    else
    Toolkit.getDefaultToolkit().beep();




    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr)
    throws BadLocationException

    // if (text == null)
    // return;
    //
    String str = text.replaceAll("\D", "");
    if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
    super.replace(fb, offset, length, str, attr);
    else
    Toolkit.getDefaultToolkit().beep();







    And the main class, App.java:



    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import javax.swing.JTextField;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.DocumentFilter;

    public class App

    private JFrame frame;
    private JTextField textField;

    /**
    * Launch the application.
    */
    public static void main(String[] args)
    EventQueue.invokeLater(new Runnable()
    public void run()
    try
    App window = new App();
    window.frame.setVisible(true);
    catch (Exception e)
    e.printStackTrace();


    );


    /**
    * Create the application.
    */
    public App()
    initialize();


    /**
    * Initialize the contents of the frame.
    */
    private void initialize()
    frame = new JFrame();
    frame.setBounds(100, 100, 191, 96);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(6, 6, 179, 62);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    textField = new JTextField();
    textField.setBounds(6, 6, 167, 26);
    panel.add(textField);
    textField.setColumns(10);

    // without this code below this, the textfield is “normal” when
    // something is selected if I write it overwrites the selection

    AbstractDocument doc = (AbstractDocument) textField.getDocument();
    doc.setDocumentFilter(new JustLimitDigitFilter(4));





    Any suggestion is welcome since I'm new to this, apart from the doubt I explicitly have.










    share|improve this question
























      0












      0








      0








      I'm working with Java and I have a JTextField which can only have 4 digits. I'm using a class that extends DocumentFilter to filter out any other character, and to limit the number of characters to 4.



      The problem is that once I have 4 digits, if I select all of them and try to overwrite them by typing another digit it doesn't auto overwrite and does nothing, I have to explicitly type "Backspace" or "Delete" in my keyboard to remove the 4 digits and then (once the field is clear) I can type again.



      How can I make the JTextField act as the rest of the operating system that once I have some text selected if I type a character it “removes all, then writes the character” (it substitutes the contents).



      I have one aux class, JustLimitDigitFilter.java:



      import javax.swing.text.DocumentFilter;
      import javax.swing.text.BadLocationException;

      import java.awt.Toolkit;

      import javax.swing.text.AttributeSet;

      public class JustLimitDigitFilter extends DocumentFilter

      int limit;

      public JustLimitDigitFilter(int limit)
      this.limit = limit;


      @Override
      public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException

      // if (text == null)
      // return;
      //
      String str = text.replaceAll("\D", "");
      if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
      super.insertString(fb, offset, str, attr);
      else
      Toolkit.getDefaultToolkit().beep();




      @Override
      public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr)
      throws BadLocationException

      // if (text == null)
      // return;
      //
      String str = text.replaceAll("\D", "");
      if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
      super.replace(fb, offset, length, str, attr);
      else
      Toolkit.getDefaultToolkit().beep();







      And the main class, App.java:



      import java.awt.EventQueue;

      import javax.swing.JFrame;
      import javax.swing.JPanel;
      import java.awt.BorderLayout;
      import javax.swing.JTextField;
      import javax.swing.text.AbstractDocument;
      import javax.swing.text.DocumentFilter;

      public class App

      private JFrame frame;
      private JTextField textField;

      /**
      * Launch the application.
      */
      public static void main(String[] args)
      EventQueue.invokeLater(new Runnable()
      public void run()
      try
      App window = new App();
      window.frame.setVisible(true);
      catch (Exception e)
      e.printStackTrace();


      );


      /**
      * Create the application.
      */
      public App()
      initialize();


      /**
      * Initialize the contents of the frame.
      */
      private void initialize()
      frame = new JFrame();
      frame.setBounds(100, 100, 191, 96);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(null);

      JPanel panel = new JPanel();
      panel.setBounds(6, 6, 179, 62);
      frame.getContentPane().add(panel);
      panel.setLayout(null);

      textField = new JTextField();
      textField.setBounds(6, 6, 167, 26);
      panel.add(textField);
      textField.setColumns(10);

      // without this code below this, the textfield is “normal” when
      // something is selected if I write it overwrites the selection

      AbstractDocument doc = (AbstractDocument) textField.getDocument();
      doc.setDocumentFilter(new JustLimitDigitFilter(4));





      Any suggestion is welcome since I'm new to this, apart from the doubt I explicitly have.










      share|improve this question














      I'm working with Java and I have a JTextField which can only have 4 digits. I'm using a class that extends DocumentFilter to filter out any other character, and to limit the number of characters to 4.



      The problem is that once I have 4 digits, if I select all of them and try to overwrite them by typing another digit it doesn't auto overwrite and does nothing, I have to explicitly type "Backspace" or "Delete" in my keyboard to remove the 4 digits and then (once the field is clear) I can type again.



      How can I make the JTextField act as the rest of the operating system that once I have some text selected if I type a character it “removes all, then writes the character” (it substitutes the contents).



      I have one aux class, JustLimitDigitFilter.java:



      import javax.swing.text.DocumentFilter;
      import javax.swing.text.BadLocationException;

      import java.awt.Toolkit;

      import javax.swing.text.AttributeSet;

      public class JustLimitDigitFilter extends DocumentFilter

      int limit;

      public JustLimitDigitFilter(int limit)
      this.limit = limit;


      @Override
      public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException

      // if (text == null)
      // return;
      //
      String str = text.replaceAll("\D", "");
      if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
      super.insertString(fb, offset, str, attr);
      else
      Toolkit.getDefaultToolkit().beep();




      @Override
      public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr)
      throws BadLocationException

      // if (text == null)
      // return;
      //
      String str = text.replaceAll("\D", "");
      if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
      super.replace(fb, offset, length, str, attr);
      else
      Toolkit.getDefaultToolkit().beep();







      And the main class, App.java:



      import java.awt.EventQueue;

      import javax.swing.JFrame;
      import javax.swing.JPanel;
      import java.awt.BorderLayout;
      import javax.swing.JTextField;
      import javax.swing.text.AbstractDocument;
      import javax.swing.text.DocumentFilter;

      public class App

      private JFrame frame;
      private JTextField textField;

      /**
      * Launch the application.
      */
      public static void main(String[] args)
      EventQueue.invokeLater(new Runnable()
      public void run()
      try
      App window = new App();
      window.frame.setVisible(true);
      catch (Exception e)
      e.printStackTrace();


      );


      /**
      * Create the application.
      */
      public App()
      initialize();


      /**
      * Initialize the contents of the frame.
      */
      private void initialize()
      frame = new JFrame();
      frame.setBounds(100, 100, 191, 96);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(null);

      JPanel panel = new JPanel();
      panel.setBounds(6, 6, 179, 62);
      frame.getContentPane().add(panel);
      panel.setLayout(null);

      textField = new JTextField();
      textField.setBounds(6, 6, 167, 26);
      panel.add(textField);
      textField.setColumns(10);

      // without this code below this, the textfield is “normal” when
      // something is selected if I write it overwrites the selection

      AbstractDocument doc = (AbstractDocument) textField.getDocument();
      doc.setDocumentFilter(new JustLimitDigitFilter(4));





      Any suggestion is welcome since I'm new to this, apart from the doubt I explicitly have.







      java swing user-interface windowbuilder documentfilter






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 17:45









      ManuelManuel

      1767 bronze badges




      1767 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          2














          Method replace() in class DocumentFilter actually performs two operations. First it removes length characters starting at offset, after which it inserts text at offset. Hence the following line in your replace() method causes nothing to happen when the JTextField contains the maximum allowable number of characters...



          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit) {


          If the JTextField is full, then its length will be the maximum number of characters, so adding the length of str will always be greater than limit.






          share|improve this answer























          • Nice! Still I'm not sure about removing the if. How would you solve it?

            – Manuel
            Mar 26 at 18:50











          • You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

            – Abra
            Mar 26 at 19:00


















          1














          Expanding on Abra's answer:



          The "length" parameter in the replace(...) method contains the number of characters that will be removed.



          So you can change your if statement to be:



          //if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length() - length) <= limit)


          After this change you can then simplify the insert(...) method to be:



          @Override
          public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
          throws BadLocationException

          replace(fb, offset, 0, text, attributes);






          share|improve this answer


















          • 1





            Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

            – Manuel
            Mar 26 at 23:01













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55363337%2fjtextfield-to-remove-characters-automatically-when-overwritting-selected%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Method replace() in class DocumentFilter actually performs two operations. First it removes length characters starting at offset, after which it inserts text at offset. Hence the following line in your replace() method causes nothing to happen when the JTextField contains the maximum allowable number of characters...



          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit) {


          If the JTextField is full, then its length will be the maximum number of characters, so adding the length of str will always be greater than limit.






          share|improve this answer























          • Nice! Still I'm not sure about removing the if. How would you solve it?

            – Manuel
            Mar 26 at 18:50











          • You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

            – Abra
            Mar 26 at 19:00















          2














          Method replace() in class DocumentFilter actually performs two operations. First it removes length characters starting at offset, after which it inserts text at offset. Hence the following line in your replace() method causes nothing to happen when the JTextField contains the maximum allowable number of characters...



          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit) {


          If the JTextField is full, then its length will be the maximum number of characters, so adding the length of str will always be greater than limit.






          share|improve this answer























          • Nice! Still I'm not sure about removing the if. How would you solve it?

            – Manuel
            Mar 26 at 18:50











          • You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

            – Abra
            Mar 26 at 19:00













          2












          2








          2







          Method replace() in class DocumentFilter actually performs two operations. First it removes length characters starting at offset, after which it inserts text at offset. Hence the following line in your replace() method causes nothing to happen when the JTextField contains the maximum allowable number of characters...



          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit) {


          If the JTextField is full, then its length will be the maximum number of characters, so adding the length of str will always be greater than limit.






          share|improve this answer













          Method replace() in class DocumentFilter actually performs two operations. First it removes length characters starting at offset, after which it inserts text at offset. Hence the following line in your replace() method causes nothing to happen when the JTextField contains the maximum allowable number of characters...



          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit) {


          If the JTextField is full, then its length will be the maximum number of characters, so adding the length of str will always be greater than limit.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 26 at 18:28









          AbraAbra

          1,75210 silver badges19 bronze badges




          1,75210 silver badges19 bronze badges












          • Nice! Still I'm not sure about removing the if. How would you solve it?

            – Manuel
            Mar 26 at 18:50











          • You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

            – Abra
            Mar 26 at 19:00

















          • Nice! Still I'm not sure about removing the if. How would you solve it?

            – Manuel
            Mar 26 at 18:50











          • You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

            – Abra
            Mar 26 at 19:00
















          Nice! Still I'm not sure about removing the if. How would you solve it?

          – Manuel
          Mar 26 at 18:50





          Nice! Still I'm not sure about removing the if. How would you solve it?

          – Manuel
          Mar 26 at 18:50













          You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

          – Abra
          Mar 26 at 19:00





          You need to check whether the final length of the text is within the limit. The final length is the current length minus the number of characters to be removed plus the length of the text to be inserted.

          – Abra
          Mar 26 at 19:00













          1














          Expanding on Abra's answer:



          The "length" parameter in the replace(...) method contains the number of characters that will be removed.



          So you can change your if statement to be:



          //if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length() - length) <= limit)


          After this change you can then simplify the insert(...) method to be:



          @Override
          public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
          throws BadLocationException

          replace(fb, offset, 0, text, attributes);






          share|improve this answer


















          • 1





            Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

            – Manuel
            Mar 26 at 23:01















          1














          Expanding on Abra's answer:



          The "length" parameter in the replace(...) method contains the number of characters that will be removed.



          So you can change your if statement to be:



          //if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length() - length) <= limit)


          After this change you can then simplify the insert(...) method to be:



          @Override
          public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
          throws BadLocationException

          replace(fb, offset, 0, text, attributes);






          share|improve this answer


















          • 1





            Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

            – Manuel
            Mar 26 at 23:01













          1












          1








          1







          Expanding on Abra's answer:



          The "length" parameter in the replace(...) method contains the number of characters that will be removed.



          So you can change your if statement to be:



          //if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length() - length) <= limit)


          After this change you can then simplify the insert(...) method to be:



          @Override
          public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
          throws BadLocationException

          replace(fb, offset, 0, text, attributes);






          share|improve this answer













          Expanding on Abra's answer:



          The "length" parameter in the replace(...) method contains the number of characters that will be removed.



          So you can change your if statement to be:



          //if (!str.isEmpty() && (fb.getDocument().getLength() + str.length()) <= limit)
          if (!str.isEmpty() && (fb.getDocument().getLength() + str.length() - length) <= limit)


          After this change you can then simplify the insert(...) method to be:



          @Override
          public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
          throws BadLocationException

          replace(fb, offset, 0, text, attributes);







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 26 at 20:58









          camickrcamickr

          281k17 gold badges132 silver badges243 bronze badges




          281k17 gold badges132 silver badges243 bronze badges







          • 1





            Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

            – Manuel
            Mar 26 at 23:01












          • 1





            Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

            – Manuel
            Mar 26 at 23:01







          1




          1





          Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

          – Manuel
          Mar 26 at 23:01





          Thanks for the explicit code, but he was first (at least in a comment), so I will accept his. In any case, +1.

          – Manuel
          Mar 26 at 23:01

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55363337%2fjtextfield-to-remove-characters-automatically-when-overwritting-selected%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript