JFormattedTextField and empty text

Hi people,

hitting an obstacle (again - the fields in text form and I will be ever friends ;-)

The requirement is quite simple: do something when you get a 'value' - changed (aka: validation) and engage in the combination of keys. The solution seems easy enough also: force a validation at each change of document. Which works very well (never forget a validation fails if the user has typed in the text, nothing happens in this case is correct). Except when you delete the last character: No. value-changed because most of the trainers don't empty card string for the null value. As I have no control on the trainer (in this case - extended SwingX NumberFormatter handles it graciously :-)) I came with a dirty trick: If a forced validation failed and the text in the field is empty, set the value to null.

Don't like... so any other ideas? I hope that I am wrong and some kind soul can point me to the right path

Thank you
Jeanette


Here's an example: to see what I mean (and probably described bad :-) remove numbers until the field is empty.) When you delete the last no modified value is triggered and transfer the focus to the button restores the text to the last valid value. Uncomment the dirt makes to behave as I want.
/*
 * Created on 25.11.2010
 *
 */
package de.javasoft.swing.jytable;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

public class FormattedNull {

    private JFormattedTextField field;

    private JComponent createContent() {
        JComponent content = new JPanel();
        field = new JFormattedTextField(new Integer(55));
        field.setColumns(20);
        field.addPropertyChangeListener(getPropertyChangeListener());
        field.getDocument().addDocumentListener(getDocumentListener());
        content.add(field);
        content.add(new JButton("just something focusable"));
        return content;
    }

    protected void maybeCommitEdit(Document document) {
        try {
            field.commitEdit();
        } catch (ParseException e) {
            // uncomment to map empty string to null
//            if (field.getText().length() == 0) {
//                field.setValue(null);
//            }
        }
    }

    private PropertyChangeListener getPropertyChangeListener() {
        PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("value".equals(evt.getPropertyName()))
                    matchValueChanged(evt.getNewValue());
            }
        };
        return propertyChangeListener;
    }

    protected void matchValueChanged(Object value) {
        System.out.println("got new value: " + value);
    }

    private DocumentListener getDocumentListener() {
        DocumentListener documentListener = new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                maybeCommitEdit(e.getDocument());
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                maybeCommitEdit(e.getDocument());
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        };
        return documentListener;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new FormattedNull().createContent());
                frame.setLocationRelativeTo(null);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

}

too bad validation fails if the user has typed in the text, nothing happens in this case is correct

So if a text is empty if it is not a valid text according to the trainer, then this is correct? So there is no problem :).

But yes my text field shaped on is the same as your solution (if authorized null):

    @Override
    public void commitEdit() throws ParseException {
        if(allowsNull() && isBlank()) {
            setValue(null);
        }
        else {
            super.commitEdit();
         }
    }

Tags: Java

Similar Questions

  • Photoshop CC 14.2 leaves empty text layer

    Hey,.

    with the new update of the CC 14.2, whenever you click anywhere with the text tool and that you change your mind (like hitting ESC because you missed an existing text) an empty text layer is left out. He didn't use to be like this, empty text layers are everywhere in my paper now.

    In any case, you can avoid this?

    (I'm on a Mac using the x 64 version of Photoshop CC 14.2)

    Yes, it's a boring change in photoshop cc 14.2

    http://feedback.Photoshop.com/photoshop_family/topics/photoshop_cc_14_2_pressing_esc_in_te xt_layer_editing_mode_doesnt_cancel_but_applies_changes

    you could press the button cancel the options toolbar or press on Ctrl + > (windows) or cmd + > (mac)

    Does anyone know if that change is actually documented anywhere?

  • How to validate and save the values to a combo box and two text boxes in flex4 mxml application with as3

    helllo all,.

    I'm working on the application web flex4 with as3.

    I have a doubt, I've created a mxml it has two text boxes, except the button and a combo box that is has two option as a percentage and the amount.

    my needs are I gave here.

    need 1: when I choose option amount that two text boxes does not have to be editable.when I select text tat box two percentage option will be editable.

    need 2: when I select the percentage in combox option and two text boxes are empty, and then click the button Save-> I want to display warning msg

    need 3: when I select the option amount combox and the two boxes are emptu click the button Save-> I don't want any warning messages.

    How to validate it and how to write backup for this function.

    any suggession or extract code is welcome.

    Thanks in advance,

    B.Venkatesan

    Looks like you are trying to do too much at once. Try to hang the events correctly

    The close event of the comboBox can do something like this

    protected function toggleTextEditing(event:DropDownEvent):void

    {

    If (this.optionCmb.selectedItem.label is "Percentage")

    {

    This.Text1.editable = true;

    This.Text2.editable = true;

    }

    Else if (this.optionCmb.selectedItem.label == "Number")

    {

    This.Text1.editable = false;

    This.Text2.editable = false;

    }

    }

    The button's click event can do something like

    protected function save(event:MouseEvent):void

    {

    If (this.optionCmb.selectedItem.label is "Percentage")

    {

    If (this.text1.text == "" & this.text2.text == "")

    {

    Alert.Show ("text is empty");

    return;

    }

    on the other

    {

    }

    }

    Else if (this.optionCmb.selectedItem.label == "Number")

    {

    }

    }

    If you can put in your entire code, maybe I can have a look to see if I can find something wrong with that.

    -Pramod

    http://www.flexmycode.com

  • 0 for empty text fields

    I've got txt_1, txt_2, etc... until txt_15. How do the '0' appears for empty text fields.

    main_btn.onRelease = function () {}

    do something and

    for (i = 0; i < 16; i ++) {}

    {if("txt_"+[i].text=="")}

    "txt_" + [i] .text = '0 '.

    }

    }

    main_btn.onRelease = function () {}

    do something and

    for (i = 0; i<16;>

    {if (this ["txt_" + i]. (Text=="")}

    This ["txt_" + i] .text = '0 '.

    }

    }
    }

  • Copy empty text boxes so that when you fill in one of the other

    I use Acrobat Professional 8.  I size a text box empty, it is automatically labeled "Text1".  I can copy the empty box by holding the CTRL key and moving the box.  Now I have 2 boxes.  If I want to do 3 boxes, I repeat this action.  The only problem is the following: all say 'Text1' and if you fill out the first box, all the other boxes are populated with the same information.  Here's my question: How can I copy empty text boxes so that this doesn't happen. in other words, how can I copy the boxes as if I fill in the first box, all the other boxes remain empty until I go and fill them?  Please, I beg you.  Thank you.

    Somethings to try:

    Each of the replicated text boxes give a unique name (Text1, Text2, Text3, etc..)

    Or placer place Text1, and then in the context menu, select "Place multiple fields".

    This replica of the first, and provides a unique name for each.

    Place each field as you wish.

    Be well...

  • Delete pages with empty text boxes that are threaded

    I tried the program and the forum and that you do not see the answer to what is probably a simple question.

    First the bottom -.

    I get files InDesign 100 + pages created with boxes of text block. I have change for a bigger and the text moves with the largest areas of text, everything as I want it.

    The problem now is, I have a lot of empty pages with empty text in them block boxes. When I try to delete the pages in the menu layout by selecting all empty it won't make more than one! (Because of the block of text boxes, I think.) There is often more than 100 when I'm through with my changes.

    Now the question-

    How can I easily get rid of the excess pages quickly?

    Thank you for your help

    Personally, I would not go the script. Course of thread should not affect the ability to remove any image and drilled it now which is threaded will cause just a nightmare on the road.

    That said, you should be able to open the pages Panel and select 'empty' pages at the same time by clicking on the first, then now Shift on the last. Then click on the trash bin icon. It is likely that you will get a warning indicating that the pages are not empty (they should have empty blocks of text on them). At this time it's OK to say go ahead and delete anyway. If you are worried, make a copy of the doc and do about it.

    If you are unable to get these pages to be deleted, it probably means that Smart Text Reflow is at work, so check if you have enabled delete empty pages in the preferences, or turn off completely. In the stop-coincidence one of these pages actually contained text put on to your pages, you will see an indicator of excess some hand (probably the last picture), then place the cursor at the end of their coaching to excess and press Ctrl (CMD on Mac) + Y to open the story editor and look to see what is actually in excess. If it is important, such as a table, for example, you need to understand why he was invisible (post another topic)., otherwise, select and then delete.

    If you are not able to delete several pages after messing around with the Smart Text Reflow settings, try replacing your preferences and check again the smart text reflow settings, and then try again.

  • erase empty text frames in the document

    I have several blocks of empty text in my documents. I want to erase them with a script.

    I have try this script but it returns an error sometimes "delete..." "not an object".

    this: (it's BAD CODE DO NOT COPY).

    {
    app.findGrepPreferences = app.changeGrepPreferences = null;

    app.findGrepPreferences.findWhat = "\\A\\Z";

    var blocsvides = app.activeDocument.findGrep (true);

    for (var i = 0; i < blocsvides.length; i ++)

    blocsvides [i] .parentTextFrames [0]. Remove() / / <-in this line, there is an error

    }

    There are a lot of images in my documents, image, text, and the indefinite object with color too.

    Thanks for helping me. :-)

    Julien.

    This should leave visible frames:

    var noColor = app.documents[0].swatches.item(0);
    var stories = app.documents[0].stories.everyItem().getElements();
    for(var i=0;i 0){continue}
          c.remove();
        }
      }
    }
    
  • Choose several folders with choosing menu and empty their contents

    Hi all

    new to applescript and want to create a file menu choose where I can choose several folders and empty their content. There will be a dialog box at the end let me know that the files have been purged. The script I'm working for an individual file:

    say application 'Finder '.

    Close each window of

    Open (choose folder with prompt "including one or more folders should purge?" multiple selections allowed location 'True' by default ' / users/bryceratops / ')

    Set an to front Finder window

    move each agenda a in the trash

    Close front The Finder window

    end say

    say application 'Finder '.

    display the dialog box buttons "purged records." {"ok"}

    end say


    But Im having this script to open, purge and close every finder window, if I selected several files in the menu choose a wire installation difficult.


    Any ideas?


    See you soon

    Hello

    Put the output of the command 'choose folder' in a variable (no need to open these folders).

    ----

    the tFolders value (choose a folder with default location "including one or more folders should purge?" guest "/ users/bryceratops / ' with multiple selections allowed)

    Tell application "Finder".

    Repeat with thisDir in tFolders

    remove items from thisDir - trash

    end repeat

    tell the end

    activate

    display the dialog buttons "purged records." {"ok"}

    ---

  • Just updated to IOS 10 and replace text does not work

    Just updated to IOS 10 and replace text does not work.  For example typing in omg should show oh my God. Has anyone else got this?

    I did the old thing: Disconnect to iCloud and sign back in. Unfortunately, he did not turn. The same thing happened on my iMac when upgrading to Mac OS Sierra - I lost all my text replacement. I also did Disconnect from iCloud and inback Panel . Unfortunately, it also didn't do the trick. Anyone know how to restore the replacement text. It is not has resided in the cloud?

  • Can I select and copy and paste text from a browser with the pencil of Apple?

    With the pencil of Apple on a new iPad Pro, I am not able to select, copy and paste text from a web page in Chrome or Safari. Y at - it a special order? A related question (not with a pencil): how to save files in PDF format.

    Well, it seems to be workin now. Never mind.

  • Why can I not send or receive SMS messages on my iPad Pro (cellular and Wi - Fi), but I can send and receive text Messages on my iPad (Wifi only) Air?

    Whey can I not send and receive SMS on my iPad Pro (cellular and Wi - Fi), but I can send and receive text Messages on my iPad (WiFi only) Air?

    You have set up on your iPad Pro of continuity?

    Continuity allows you to connect your iPhone, iPad, iPod touch and Mac - Apple Support

  • How to change the space between folder icon and the text on the personal toolbar?

    I have some files in the personal toolbar with just a letter to indicate what they are, but on the theme that I use, the letter is too far from the record, it belongs to and partially falls under following folder icon. I don't want to increase the space between all the icons to show the full letter, as this decreases the amount of icons that you can have in the toolbar. Instead, I want to reduce the space between the file and the text belonging to him, so he is right next to him instead of 5 pixels away.

    I found various entries to change the padding and margins in userChrome.css, but it's always around the icon, I don't know where to look to close the space between the icon and the corresponding text.

    Any help would be greatly appreciated, thank you.

    Did you check the value of the left margin of the text?

    You can set if necessary negative margin values.

    #PlacesToolbarItems .toolbarbutton-text { margin-left: -2px !important; }

    Add .bookmark-item [container] If this enough for the items in the folder

    #PlacesToolbarItems .bookmark-item[container] .toolbarbutton-text { margin-left: -2px !important; }
  • With Firefox 12 I'm impossible to drag-and-drop text in the text boxes or search bars. Is there a way to activate this feature?

    Firefox 11 allowed drag-and - drop text and the other two programs inside the browser itself. in FF12, I can do neither. How to restore this function?

    I had this problem too and couldn't add or move bookmarks either. If you have torbutton add-on installed, try disabling the addon. Perhaps it is caused by another addon

  • Why the blue search bar and the text does not?

    It started today, but I had this problem in the past before the last update of Firefox. Whenever I click on the search bar, it highlights with a blue background and no text shows. If I make a mistake, I can't see it.

    Firefox did the time you updated and it crashed whenever I did anything. Your last update seems to have solved the chrashing, but the blue bar with NO text is back.

    This problem may be caused by Comcast constant guard (protection of hits)

  • Accidentally deleted important image and emptied trash.

    Hello

    I can't believe I can get this stupid and delete by mistake important moments of my family and empty the trash right afterwards. Is anyway to get them back? I had about 1800 files, of which 90% are videos photos and 10%. Important thing to note here is that I'm using macbook pro with ssd, this isn't a typical hard drive that worries me even more. Given that I just read SSDS erase data immediately and allocates space for reuse. I immediately to foce minutes off my SUST after deletion have not used since.

    I want to punch me in the face. They have been all year of memories with my family and the woman. It also includes pictures of vacation am deeply saddened by this situation.

    Please let me know if mac has any built-in tool for recovering of ssd? Or any other software that relies on the ground for Mac ssd.

    When you delete files on an SSD, they are all GONE.

    Buy yourself a large but slow (USB-2 is fine), external hard drive and turn on Time machine. Don't end up in this position again.

Maybe you are looking for

  • Qosmio G20-139: What cable I need to connect a 5.1 system speakers?

    Hi all Does anyone know which cable or connector, I need to connect my Qosmio g20-139 to a 5.1 system speakers? I searched the forum and it seems that someone has used a "optical cable Toslink" - check link below: http://forums.computers.Toshiba-Euro

  • How to reset the BIOS on HP Mini 2102 password

    I have not used this laptop for awhile because it is too slow.  I just bought a new SSD to use on this laptop.  I tried to start it in the BIOS, but I can't remember what password I used on this computer.  I wonder if there is a way I can reset or re

  • What events trigger service requests?

    Hello I know that CHS has algorithms to assess the communications between the sophisticated devices but, is there an easy solution for a customer who asks what events trigger Service requests? Kind regards Gabriel Tlalpachicatl

  • Open usb device

    No I can open a disco duro external LG, no sales the option of 'open' in el devices panel e printers. As puedo hacer? Please thanks.

  • BlackBerry Smartphones assigning a tone "SMS"?

    Good if I learned how to put an MP3 song as a ringtone, it was pretty easy. But is he in any case of assignment of a MP3 file as a text Message tone? I had a specific, on my old phone which, along w / all my other MP3s came with me when I went to the