• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

JFormattedTextField

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Can anybody tell me about how to use the JFormattedTextField. I want to have a TextField which is formatted as "(###) ###-####". I tried using



I dont know how to continue later, when i run the application, the field is displayed as (###) ###-#### But when i write numbers into that say 123456789, it is taking the numbers as it is and is not converting into that format.

I want the user to enter only the numbers and not the brackets ('(') and all. He should just enter the numbers but the UI should take or display in (123) 435-3456 format.

How do i do that? Does anybody have code about this or does anybody can give me idea as to how to go about in doing this.

I am new to Swing concepts. So as such i am asking for it

I would be thankful if anybody helps me

thanks and regards
smriti
 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Write the code as follows, it will work :



Cheers.
Kiran
 
Smriti Anchu
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Kiran

I tried with ur code. It is working fine. But now i have a problem.

a. I am not able to leave the text field blank. Once i delete the value in the text field and go to next field. It displays old number.
b. When i select the whole field and press delete, THe format also gets deleted So as such when i enter a new value, it is not taken in the right format and last saved value is displayed

How do i handle this?

thanks and regards
smriti
 
kiran raja
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Actually Smriti,You could override the insertString method of the PlainDocument of the text field, by extending PlainDocument, and
then call setDocument() on your JTextField to assign it the new
document model.But since you are new to Swing, i prefer you dont take a hard way round.
So try using the following code.



with regards
Kiran.
 
Smriti Anchu
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi kiran,

Thanks a lot. I made the code work, by calling the key listener. Setting format again if delete key is pressed and a huge code i hv written. I shall try with yours now. Right now it is working.

I just have some doubts in JFormattedTextField

1. Cant we not disable the textfield, i tried using

When i run the applicaiton ,i found that the text field is enabled even after setting it to false. This happens only for the first time. I have 2 buttons one to enable and other to disable. So when i click on the enable button all the fields are enabled and when i click disable button then at that time, the all the fields and also JFormattedTextfield gets disabled. The same code is called when the screen is first displayed. But it is not displaying. I donno what could be wrong.
 
Smriti Anchu
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Kiran,

the phone number is displayed in the format i want, but when i press back space button, it gets erased including the format. How do i maintain the format when pressing the back space button. This happens only for the first time when it is retrieved from the datebase. For the second time and all, once i press backspace, it is not deleting the format.
Kindly tell me how to go with this

thanks and regards
smriti
 
kiran raja
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Smriti,
I am giving you an example program.I have tried to reproduce your problem.This program is working fine on my system. With this i hope all your problems come to an end.

Wishing you all Success.

With regards ,
Kiran


import java.awt.*;
import java.awt.event.*;
import java.text.*;// NEW
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;// NEW

import dl.*;

public class TextDemo extends JFrame {
protected JFormattedTextField m_firstTxt;// NEW
protected JFormattedTextField m_lastTxt;
protected JFormattedTextField m_phoneTxt;
protected JFormattedTextField m_faxTxt;
protected JPasswordField m_passwordTxt;
protected JTextArea m_commentsTxt;// NEW
protected JLabel m_status;

public static final String PHONE_PATTERN = "(###)###-####";

public TextDemo() {
super("Text Components Demo");
Font monospaced = new Font("Monospaced", Font.PLAIN, 12);
JPanel pp = new JPanel(new BorderLayout());

JPanel p = new JPanel(new DialogLayout2());
p.setBorder(new EmptyBorder(10, 10, 10, 10));
p.add(new JLabel("First name:"));
m_firstTxt = new JFormattedTextField(
new NameFormat());// NEW
m_firstTxt.setInputVerifier(new TextVerifier(
"First name cannot be empty"));
m_firstTxt.setColumns(12);
p.add(m_firstTxt);

p.add(new JLabel("Last name:"));
m_lastTxt = new JFormattedTextField(
new NameFormat());// NEW
m_lastTxt.setColumns(12);
p.add(m_lastTxt);

p.add(new JLabel("Phone number:"));// NEW
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(PHONE_PATTERN);
}
catch (ParseException pex) {
pex.printStackTrace();
}
m_phoneTxt = new JFormattedTextField(formatter);
m_phoneTxt.setColumns(12);
m_phoneTxt.setInputVerifier(new FTFVerifier(
"Phone format is "+PHONE_PATTERN));
p.add(m_phoneTxt);

p.add(new JLabel("Fax number:"));// NEW
m_faxTxt = new JFormattedTextField(
new PhoneFormat());
m_faxTxt.setColumns(12);
m_faxTxt.setInputVerifier(new FTFVerifier(
"Fax format is "+PHONE_PATTERN));
p.add(m_faxTxt);

p.add(new JLabel("Login password:"));
m_passwordTxt = new JPasswordField(20);
m_passwordTxt.setFont(monospaced);
m_passwordTxt.setInputVerifier(new TextVerifier(
"Login password cannot be empty"));
p.add(m_passwordTxt);

p.setBorder(new CompoundBorder(
new TitledBorder(new EtchedBorder(), "Personal Data"),
new EmptyBorder(1, 5, 3, 5))
);
pp.add(p, BorderLayout.NORTH);

m_commentsTxt = new JTextArea("", 4, 30);
m_commentsTxt.setFont(monospaced);
m_commentsTxt.setLineWrap(true);
m_commentsTxt.setWrapStyleWord(true);
p = new JPanel(new BorderLayout());
p.add(new JScrollPane(m_commentsTxt));
p.setBorder(new CompoundBorder(
new TitledBorder(new EtchedBorder(), "Comments"),
new EmptyBorder(3, 5, 3, 5))
);
pp.add(p, BorderLayout.CENTER);

m_status = new JLabel("Input data");
m_status.setBorder(new CompoundBorder(
new EmptyBorder(2, 2, 2, 2),
new SoftBevelBorder(SoftBevelBorder.LOWERED)));
pp.add(m_status, BorderLayout.SOUTH);
Dimension d = m_status.getPreferredSize();
m_status.setPreferredSize(new Dimension(150, d.height));

pp.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(pp);
pack();
}

public static void main(String[] args) {
JFrame frame = new TextDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

/**
* Format which capitalize all words
*/
class NameFormat extends Format {

public StringBuffer format(Object obj, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(toAppendTo.length());
String str = obj.toString();
char prevCh = ' ';
for (int k=0; k<str.length(); k++) {
char nextCh = str.charAt(k);
if (Character.isLetter(nextCh) && prevCh == ' ')
nextCh = Character.toTitleCase(nextCh);
toAppendTo.append(nextCh);
prevCh = nextCh;
}
fieldPosition.setEndIndex(toAppendTo.length());
return toAppendTo;
}

public Object parseObject(String text, ParsePosition pos) {
pos.setIndex(pos.getIndex()+text.length());
return text;
}
}

/**
* Format phone numbers
*/
class PhoneFormat extends Format {

public StringBuffer format(Object obj, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(toAppendTo.length());

// Gen digits of the number
String str = obj.toString();
StringBuffer number = new StringBuffer();
for (int k=0; k<str.length(); k++) {
char nextCh = str.charAt(k);
if (Character.isDigit(nextCh))
number.append(nextCh);
else if (Character.isLetter(nextCh)) {
nextCh = Character.toUpperCase(nextCh);
switch (nextCh) {
case 'A':
case 'B':
case 'C':
number.append('2');
break;
case 'D':
case 'E':
case 'F':
number.append('3');
break;
case 'G':
case 'H':
case 'I':
number.append('4');
break;
case 'J':
case 'K':
case 'L':
number.append('5');
break;
case 'M':
case 'N':
case 'O':
number.append('6');
break;
case 'P':
case 'Q':
case 'R':
case 'S':
number.append('7');
break;
case 'T':
case 'U':
case 'V':
number.append('8');
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
number.append('9');
break;
}
}
}

// Format digits according to the pattern
int index = 0;
for (int k=0; k<PHONE_PATTERN.length(); k++) {
char ch = PHONE_PATTERN.charAt(k);
if (ch == '#') {
if (index >= number.length())
break;
toAppendTo.append(number.charAt(index++));
}
else
toAppendTo.append(ch);
}

fieldPosition.setEndIndex(toAppendTo.length());
return toAppendTo;
}

public Object parseObject(String text, ParsePosition pos) {
pos.setIndex(pos.getIndex()+text.length());
return text;
}
}

/**
* Verify input to JTextField
*/
class TextVerifier extends InputVerifier {
private String m_errMsg;

public TextVerifier(String errMsg) {
m_errMsg = errMsg;
}

public boolean verify(JComponent input) {
m_status.setText("");
if (!(input instanceof JTextField))
return true;
JTextField txt = (JTextField)input;
String str = txt.getText();
if (str.length() == 0) {
m_status.setText(m_errMsg);
return false;
}
return true;
}
}

/**
* Verify input to JFormattedTextField
*/
class FTFVerifier extends InputVerifier {
private String m_errMsg;

public FTFVerifier(String errMsg) {
m_errMsg = errMsg;
}

public boolean verify(JComponent input) {
m_status.setText("");
if (!(input instanceof JFormattedTextField))
return true;
JFormattedTextField ftf = (JFormattedTextField)input;
JFormattedTextField.AbstractFormatter formatter =
ftf.getFormatter();
if (formatter == null)
return true;
try {
formatter.stringToValue(ftf.getText());
return true;
}
catch (ParseException pe) {
m_status.setText(m_errMsg);
return false;
}
}
}
}
 
kiran raja
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Smriti,
I am giving you an example program.I have tried to reproduce your problem.This program is working fine on my system. With this i hope all your problems come to an end.

Wishing you all Success.

With regards ,
Kiran

 
kiran raja
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is the custom Dialog i have used in my program.....


-Kiran


 
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic