Bob
Bob

Reputation: 141

Escape character in JTextfield

I was wondering if there's a simple way to deal with escape characters in a JTextField. The thing is that getText() will escape the escape character. Of course, that will be the preferred behavior most of the time, but not if you want to allow the users to freely provide a delimiter for a CSV file (including \t). Any ideas?

Bob

Upvotes: 0

Views: 1204

Answers (3)

Alex-v-s
Alex-v-s

Reputation: 187

I know this may be kind of late for you, but I found an easy solution to that problem:

JTextfield field = new JTextField();
/*someone puts a string into it*/
escapeFulString = field.getText().replace("\\t","\t");
System.out.println(escapeFulString);

This will print out that string with all the tabs. To add any other escape sequences just do that same process. Just don't forget, java string methods DO NOT edit in place, e.g.:

text.replace("\\t","\t") 
//is not the same as
text = text.replace("\\t","\t");

Upvotes: 0

Michał Kupisiński
Michał Kupisiński

Reputation: 3863

JTextField is only a View so it always has a model inside it, this model is Document class. You can try this:

    JTextField f = new JTextField();

    // your JTextField is being filled somehow with text ...

    Document document = f.getDocument();
    try {
        String text = document.getText(0, document.getLength());
    } catch (BadLocationException ex) {
    }

Maybe when you collect text from Document instance instead of JTextField instance it won't be escaped;

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25725

You can always override the behavior of any and all public functions in a swing component. Its called "specialization". For example, you can create your own MyJTextField class and override the getText() method.

Upvotes: 1

Related Questions