Format JTextField

How can I format the JTextField to receive a certain input String like currency or decimal point. I know that I can write a function to validate those strings but it is more convinient to user if the text field just let them replace string of zero like Visual Basic.

Use this class..
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusListener;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class JFormattedField extends JTextField implements ActionListener, FocusListener {
private NumberFormat format;
public JFormattedField() {
     this(0.0, 8, new java.text.DecimalFormat("0.00000"));
public JFormattedField(String value, int columns) {
     this(value, columns, new java.text.DecimalFormat("0.00000"));
public JFormattedField(String value, int columns, NumberFormat f) {
     this(Double.parseDouble(value), columns, f);
public JFormattedField(double value, int columns, NumberFormat f) {
super(columns);
format = f;
     setHorizontalAlignment(JTextField.RIGHT);
     addActionListener(this);
     addFocusListener(this);
setValue(value);
public void focusGained(java.awt.event.FocusEvent f) { }
public void focusLost(java.awt.event.FocusEvent f) {
     try {
     if (!f.isTemporary())
          setValue(Double.parseDouble(getText()));
     } catch (NumberFormatException ne) {
          Toolkit.getDefaultToolkit().beep();
public void actionPerformed(ActionEvent a) {
     try {
     setValue(Double.parseDouble(a.getActionCommand()));
     } catch (NumberFormatException ne) {
     Toolkit.getDefaultToolkit().beep();
public double getValue() {
double retVal = 0.0;
try {
retVal = format.parse(getText()).doubleValue();
} catch (ParseException e) {
Toolkit.getDefaultToolkit().beep();
return retVal;
public void setValue(double value) {
setText(format.format(value));
public void setValue(String value) {
setText(value);
protected Document createDefaultModel() {
return new NumberDocument(format);
private class NumberDocument extends PlainDocument {
     NumberFormat format;
     NumberDocument(NumberFormat f) {
     this.format = f;
public void insertString(int offset, String string, AttributeSet as) throws BadLocationException {
     final String NUMBERS = "-.,0123456789";
     try {
          char [] src = string.toCharArray();
          char [] dest = new char[src.length];
          int count=0;
          for (int i=0; i<src.length; i++)
          if (NUMBERS.indexOf(src) != -1)
               dest[count++] = src[i];
          super.insertString(offset, new String(dest, 0, count), as);
     } catch (Exception e) {
          e.printStackTrace(System.err);
Sample test program...
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
import tools.*;
public class Field extends JFrame {
public Field() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 1));
panel.add(new JFormattedField(0.0,11,new java.text.DecimalFormat("0.00000")));
panel.add(new JFormattedField(0.0,11,new java.text.DecimalFormat("0.00")));
panel.add(new JFormattedField("1",11,new java.text.DecimalFormat("0.00")));
getContentPane().add(panel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
pack();
public static void main(String[] args) {
(new Field()).show();
Hope it helps..
[email protected]

Similar Messages

  • Formatted JTextField

    I am currently writing an Swing application where the user at some point should type in some line of text (no line breaks) in a JTextField.
    Since the allowed input should only be some sequence of words (only characters A-Z,a-z and 0-9 and space allowed), I think it might be useful for the user to format the input while he types:
    - automatically changing each letter to it's lowecase version
    - drawing a box around each word, which might be tricky (the meaning is to make a clear distinction between each word, I'd be happy with an undeline and/or a change in background color for each sequence of non-space characters or chage of foreground color of each first letter of a word)
    - a relative small space just to make a 'suggestion' of a word-separation. I mean a space like about half of the with of a normal space.
    Can I achieve this in some way?
    The first point is quite easy done with the use of a custom Document-implementation and attach it as a default model to the JTextField.
    For the other two points I thought of creating a custom Font (derivating of the Font obtained by getFont()) with size/background/foreground/underline and such set accordingly.
    Problem however I get a runtime-exception when I try to do something like the following:
    public class LineInputField extends JTextField {
         private static final long serialVersionUID = 5666439466966669064L;
         public LineInputField() {
              super();
              Map<TextAttribute, Object> map = new HashMap<TextAttribute, Object>();
              map.put(TextAttribute.FAMILY, new String("SansSerif"));
              map.put(TextAttribute.POSTURE, new Float(0.2));
              map.put(TextAttribute.WEIGHT, new Float(2.0));
              map.put(TextAttribute.BACKGROUND, new Color(0.5f, 0.5f, 1.0f));
              setFont(getFont().deriveFont(map));
         protected Document createDefaultModel() {
              return new UpperCaseDocument();
         static class UpperCaseDocument extends PlainDocument {
              private static final long serialVersionUID = -3155661465030970489L;
              public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                   if (str == null) {
                        return;
                   super.insertString(offs, str.toLowerCase(), a);
    }I get:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Zero length string passed to TextLayout constructor.
         at java.awt.font.TextLayout.<init>(TextLayout.java:364)
         at sun.font.FontDesignMetrics.charsWidth(FontDesignMetrics.java:487)
         at javax.swing.text.Utilities.getTabbedTextWidth(Utilities.java:256)
         at javax.swing.text.Utilities.getTabbedTextWidth(Utilities.java:191)
         at javax.swing.text.PlainView.getLineWidth(PlainView.java:643)
         at javax.swing.text.PlainView.calculateLongestLine(PlainView.java:620)
         at javax.swing.text.PlainView.updateMetrics(PlainView.java:192)
         at javax.swing.text.PlainView.setSize(PlainView.java:464)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1701)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:904)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1627)
         at javax.swing.JTextField.getPreferredSize(JTextField.java:407)
         at java.awt.GridBagLayout.GetLayoutInfo(GridBagLayout.java:1092)
         at java.awt.GridBagLayout.getLayoutInfo(GridBagLayout.java:893)
         at java.awt.GridBagLayout.preferredLayoutSize(GridBagLayout.java:713)
         at java.awt.Container.preferredSize(Container.java:1616)
         at java.awt.Container.getPreferredSize(Container.java:1601)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1629)
         at view.layout.BoundedTableLayout.setCellInfo(BoundedTableLayout.java:193)
         at view.layout.BoundedTableLayout.addLayoutComponent(BoundedTableLayout.java:117)
         at java.awt.Container.addImpl(Container.java:1068)
         at java.awt.Container.add(Container.java:903)
         at view.panel.clss.HTKPropertiesPanel.setup(HTKPropertiesPanel.java:55)
         at view.panel.clss.HTKPropertiesPanel.<init>(HTKPropertiesPanel.java:24)
         at view.panel.HTKPanel.getPTYPanel(HTKPanel.java:86)
         at view.panel.HTKPanel.getLMPTabs(HTKPanel.java:61)
         at view.panel.HTKPanel.setup(HTKPanel.java:43)
         at view.panel.HTKPanel.<init>(HTKPanel.java:30)
         at view.TGApp.getTTREditPanel(TGApp.java:216)
         at view.TGApp.getFrame(TGApp.java:80)
         at view.TGApp.access$0(TGApp.java:67)
         at view.TGApp$1.run(TGApp.java:62)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Any suggestions/ideas/help?
    Thanks in advance.
    S.

    Can't post my whole project here, so I've made a little test prog giving the same error.
    import java.awt.Color;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.font.TextAttribute;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    public class FontApp {
         private JFrame frame;
         private JPanel contentPane;
         public FontApp() {
              this.frame = null;
              this.contentPane = null;
         private JFrame getFrame() {
              if (frame == null) {
                   frame = new JFrame();
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setSize(300, 100);
                   frame.setContentPane(getContentPane());
                   frame.setTitle("Font test");
              return frame;
         private JPanel getContentPane() {
              if (contentPane == null) {
                   contentPane = new JPanel();
                   contentPane.setLayout(new GridBagLayout());
                   GridBagConstraints gbc = new GridBagConstraints();
                   gbc.fill = GridBagConstraints.NONE;
                   gbc.insets.left = 5;
                   gbc.insets.right = 5;
                   contentPane.add(new JLabel("line: "), gbc);
                   gbc.fill = GridBagConstraints.HORIZONTAL;
                   gbc.gridx = 1;
                   gbc.weightx = 1;
                   gbc.insets.left = 0;
                   contentPane.add(new LineInputField(), gbc);
              return contentPane;
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        FontApp application = new FontApp();
                        application.getFrame().setVisible(true);
         private static class LineInputField extends JTextField {
              private static final long serialVersionUID = 5666439466966669064L;
              public LineInputField() {
                   super();
                   Map<TextAttribute, Object> map = new HashMap<TextAttribute, Object>();
                   map.put(TextAttribute.FAMILY, new String("SansSerif"));
                   map.put(TextAttribute.POSTURE, new Float(0.9));
                   map.put(TextAttribute.WEIGHT, new Float(2.0));
                   // map.put(TextAttribute.BACKGROUND, new Color(0.5f, 0.5f, 1.0f));
                   setFont(getFont().deriveFont(map));
              protected Document createDefaultModel() {
                   return new LowerCaseDocument();
              static class LowerCaseDocument extends PlainDocument {
                   private static final long serialVersionUID = -3155661465030970489L;
                   public void insertString(int offs, String str, AttributeSet a)
                             throws BadLocationException {
                        if (str == null) {
                             return;
                        super.insertString(offs, str.toLowerCase(), a);
    }when de-commenting the line
    // map.put(TextAttribute.BACKGROUND, new Color(0.5f, 0.5f, 1.0f));in the constructor of LineInputField, the error it gives is (actually it is given twice in one single run):
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Zero length string passed to TextLayout constructor.
         at java.awt.font.TextLayout.<init>(TextLayout.java:364)
         at sun.font.FontDesignMetrics.charsWidth(FontDesignMetrics.java:487)
         at javax.swing.text.Utilities.getTabbedTextWidth(Utilities.java:256)
         at javax.swing.text.Utilities.getTabbedTextWidth(Utilities.java:191)
         at javax.swing.text.PlainView.getLineWidth(PlainView.java:643)
         at javax.swing.text.PlainView.calculateLongestLine(PlainView.java:620)
         at javax.swing.text.PlainView.updateMetrics(PlainView.java:192)
         at javax.swing.text.PlainView.setSize(PlainView.java:464)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1701)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:904)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1627)
         at javax.swing.JTextField.getPreferredSize(JTextField.java:407)
         at java.awt.GridBagLayout.GetLayoutInfo(GridBagLayout.java:1092)
         at java.awt.GridBagLayout.getLayoutInfo(GridBagLayout.java:893)
         at java.awt.GridBagLayout.ArrangeGrid(GridBagLayout.java:2048)
         at java.awt.GridBagLayout.arrangeGrid(GridBagLayout.java:2008)
         at java.awt.GridBagLayout.layoutContainer(GridBagLayout.java:789)
         at java.awt.Container.layout(Container.java:1432)
         at java.awt.Container.doLayout(Container.java:1421)
         at java.awt.Container.validateTree(Container.java:1519)
         at java.awt.Container.validateTree(Container.java:1526)
         at java.awt.Container.validateTree(Container.java:1526)
         at java.awt.Container.validateTree(Container.java:1526)
         at java.awt.Container.validate(Container.java:1491)
         at java.awt.Window.show(Window.java:820)
         at java.awt.Component.show(Component.java:1419)
         at java.awt.Component.setVisible(Component.java:1372)
         at java.awt.Window.setVisible(Window.java:801)
         at FontApp$1.run(FontApp.java:65)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

  • Formatting JTextField text

    I want to take the text of a JTextField and save it on the file system formatting with character length limited to a certain amount per line (say 77) and save any blank lines the user enters. Does anyone have any code samples how they accomplished this

    Hello Alexa,
    this is not precisely your format, but it might do as well:
    import java.awt.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class Decimal1
      public static void main(String[] args)
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(200,130);
        f.setLocation(400,300);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        f.getContentPane().add(panel);
    //  Unfortunately not every format can be used. Try e.g. ("##,000.0");
        DecimalFormat df = new DecimalFormat("##,##0.0");
        NumberFormatter nfr= new NumberFormatter(df);
        nfr.setAllowsInvalid(false);
        JFormattedTextField ftf = new JFormattedTextField(nfr);
        JLabel lFtf = new JLabel("JFormattedTextField");
        JLabel lTf = new JLabel("JTextField");
        JTextField tf = new JTextField(8);
        panel.add(lFtf);
        panel.add(ftf);
        panel.add(lTf);
        panel.add(tf);
        f.setVisible(true);
    }Regards
    J�rg

  • Date formatted JTextField

    How can I create an uneditable date formatted (00/00/0000) textfield, which allows user to type only numbers
    Numbers allowed in the first offset - 0-3
    Numbers allowed in the second offset - 0-9
    "/" in the third offset should not be deleted
    Numbers allowed in the fourth offset - 0,1
    Numbers allowed in the fifth offset - 0-9
    "/" in the sixth offset should not be deleted
    Number allowed in the seventh offset - 2
    Number allowed in the eighth offset - 0
    Number allowed in the ninth offset - 0
    Numbers allowed in the tenth offset - 6-9
    textfield MUST not allow the user to delete both zero and slash(/)
    Need Urgent help....

    I think it depends what version of SDK are you using... If you are using 1.4 or later, then you should check out the JFomatterTextField class...
    I had to do this before the 1.4, and I extended the JTextField and implements KeyListener and FocusListener; and also extended the PlainDocument for something similar. The JFormatterTextField should be much easier.

  • Format decimal values by using comma

    hi,
    Can anyone tell me how to format decimal value in JTextField by using comma. Since this JTextField is used to display amount,so i would like to put comma after three digits. That means it should look like this : 100,000,000.00. This JTextField is the total of another 9 JTextField values, that means when i edit values in another JTextField, the total value will be upated as well. I have used KeyEvent to do so , now i just have no idea how to apply comma in the total. Thanks for any help.
    Regards,
    marcalena

    Hmm....
    First off, this is not ideal... I would seriously consider updating your JRE...
    public class MyDecimalDocument extends javax.swing.text.PlainDocument
    ///init code
    public void insertString(int offset, String newString, javax.swing.text.AttributeSet set) throws javax.swing.text.BadLocationException
    //code to handle the inserts and restrict/apply various formatting....
    }Or check out [url http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp_name=Swing&qp=forum%3A57&qt=formatting+JTextField]this search for more...
    :)

  • Date format in a JTextField

    I have created 2 jtextfields to enter a start and stop date for printing a report within the date range selected. How do format the jtextfields to insure they are properly date formatted i.e. MM/dd/yyyy
    Thanks, William

    If you create an input binding of Formatted Text Field, you can specify the format mask by right-clicking the binding and clicking "Edit" from the structure pane. Then select "Format" and set whatever date format you need. This is true in 10.1.2, so it might not be available depending on what version you are using.

  • Validating JTextField for Date Format

    hello,
    everybody.
    i am trying to perform a validation on text field, i.e if the input is in a date format then it will show, other wise it will consume the character.
    please help me out of this problem i am stucked with it.
    waitng for reply. the following is my code.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JTextField(5);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
         public void keyPressed(KeyEvent ke)
              DateFormat df;
              df = DateFormat.getDateInstance();
              df = (DateFormat) ke.getSource();
              if(!(df.equals(date)))
                   ke.consume();
         public void keyReleased(KeyEvent ke)
    }

    hi,
    thanks very much, u gave me great idea.
    according to ur suggestion i used JFormattedTextField as well as SimpleDateFormat, but while giving keyevent i am getting the error,
    so please if possible reply for this.
    the error is
    java.lang.ClassCastException
         at RilJDateField.keyTyped(RilJDateField.java:61)
         at java.awt.Component.processKeyEvent(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and my source code is
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JFormattedTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         SimpleDateFormat formatter;
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JFormattedTextField();
              text.setColumns(10);
              formatter = new SimpleDateFormat("dd mm yyyy");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
              Date date = (Date) ke.getSource();
              if(!(date.equals(formatter)))
                   ke.consume();
         public void keyPressed(KeyEvent ke)
         public void keyReleased(KeyEvent ke)
    }

  • How set the format of map scale(e.g. 1/2000) in the JTextField?

    Hi, folks. My company buy a third party component, it contains a scale editor which is subclass of JTextField. However, I don't why this map scale editor allows people to entry number , ,alpha and space in it(it means every letter shown on the keyboard can be typed in the scale editor). My just want to know to how to set the certain format to let people to only type in the following format: 1/200000.
    By the way, because it is part of the third party component, so all I can do is get the instance of the JTextField from the component and set the format to it.
    Thanks in advance.

    Hi, folks. My company buy a third party component, it contains a scale editor which is subclass of JTextField. However, I don't why this map scale editor allows people to entry number , ,alpha and space in it(it means every letter shown on the keyboard can be typed in the scale editor). My just want to know to how to set the certain format to let people to only type in the following format: 1/200000.
    By the way, because it is part of the third party component, so all I can do is get the instance of the JTextField from the component and set the format to it.
    Thanks in advance.

  • How can i format a JTextField to a Date format?

    How can i do to format a JTextField to a date format, may be with a mask, wich is the way to do this?

    What exactly do u mean by formatting a JTextField to date?
    Is it like - what ever the user enters should be stored as date?
    Could you explain in more detail what exactly you want the function to do?
    Best,
    Radha

  • How do I limit user to put certain format in JTextField

    I want to create a JTextField which will limit user to put date format only like (##/##/####) a date format. how do I do it? thanks

    boosta,
    Are you limited to a text based interface? I mean why not a visual calendar control?
    I just googled "java calendar control" and came up with http://builder.com.com/5100-6370-1045263.html and http://www.toedter.com/en/jcalendar/ on the first page...
    If you must use a JTextField you'll need to use EventListener(s) to filter keyboard input... I've never tried it... I've never had to.... and if this is not specific stated requirement then I'd drop it like a gun.
    I (like many other users) hate fancy custom interfaces which don't behave as you expect... and I (like many other users) am just to lazy to RTFM.
    keith.

  • Accepting date in JTextField and converting to date format

    I'm trying to convert JTextField value to date format but I can't. I need to send date value to a date field of database. Could anyone help me convert JTextField value to Date value?
    Thanks

    Date SimpleDateFormat.parse(String) ?

  • JTextField - Show date format mask while inputing

    I have searched through the forums and I have not found an instance of someone try to show the format mask while a user inputs chars:
    ex: **/**/**** <-- Initialized
    1*/**/**** <-- After first integer
    10/3*/**** <-- After third integer
    I would also like the keep the caret position at the last integer and not always at the end of the input.
    Also if a user enters a "t"||"T" that it will automatically enter today's date.
    Is there a quick way? I have tried to use a DefaultStyledDocument but have not had success.
    Thanks

    here's a starter
    (needs to handle backspace, delete and probably a few other keys)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    class Testing extends JFrame
      JTextField tf = new JTextField(new MyDoc(),"**/**/**",10);
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        jp.add(tf);
        getContentPane().add(jp);
        pack();
      class MyDoc extends PlainDocument
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
          if(str.equals("**/**/**") == false && (offs == 2 || offs == 5 ||
             str.length() > 1 || offs > 7 || "0123456789".indexOf(str) < 0))
            java.awt.Toolkit.getDefaultToolkit().beep();
            return;
          StringBuffer newText = new StringBuffer(getText(0,getLength()));
          if(newText.length() > 0)
            newText.setCharAt(offs,str.toCharArray()[0]);
            remove(0,getLength());
            super.insertString(0,newText.toString(),a);
            if(offs == 1 || offs == 4) tf.setCaretPosition(offs+2);
            else tf.setCaretPosition(offs+1);
          else super.insertString(offs,str,a);
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to JTextField to password display format

    All,
    May I know how to set the following to password display format:
    final JTextField textPassword = new JTextField(10);
    I mean when user keys in password, the password will be display as "*****".
    Thanks in advance.

    Sorry, should use JPasswordField instead of JTextField.

  • Output formatted number to jTextField

    I am new to Java and am building a desk top application. I perform the calculations and get the correct answer in the jTextField; however, I have been unable to get the answers to format. The numbers are "doubles" at this point in the calculations. I have tried several different variations of the code I am posting below and nothing works. All the answers I have found on the web and in books are set up for a System.out.println() answer as opposed to putting the answer in a jTextField. I believe the problem is between the formatting and putting the answer into the jTextField, but am uncertain. I would appreciate any suggestions to alleviate this problem.
    Thanks - Bob
    if ( M1 > M2) {
    NumberFormat numberFormat = NumberFormat.getInstance();
    DecimalFormat decimalFormat = (DecimalFormat)numberFormat;
    decimalFormat.applyPattern("0.### ### ### ### ### ### ###");
    jTextField3.setText(String.valueOf(MDiff));
    jTextField4.setText(String.valueOf(EDiff));
    else {
    NumberFormat numberFormat = NumberFormat.getInstance();
    DecimalFormat decimalFormat = (DecimalFormat)numberFormat;
    decimalFormat.applyPattern("###,###,###,###,###,###,###");
    jTextField3(setText(String.valueOf(MDiff));
    jTextField4.setText(String.valueOf(EDiff));
    }

    The numbers are entered as text, and then converted to a "float" variable. They are then changed to "double" and multiple computations take place. The code that I posted is after the computations of MDiff and EDiff, and covered the "logical if" where I test to see which of two numbers from the initial data entry was larger and format appropriately. There was error in my post which I have corrected. The error was in the 4th line below "else" where it states: "jTextField3(set....." I have changed it to read "jtTextField3.set....", and it builds without error. Sorry about that.
    As previously stated, I get correct answers from the computations, but am unable to format the answers.
    Bob

  • Formatting a JTextField...

    Why doesn't this work !!!!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.JComponent.*;
    import java.awt.Color.*;
    import java.awt.Font.*;
    //...... more code here
    input1TextField = new JTextField(10);
    //....... more code here
    input1TextField.setFont(ITALIC);I have been looking at the relevant API documents and this is what I've deduced:
    JTextField is a class which extends javax.swing.text.JTextComponent and has a method: setFont (Font f)
    Looking at the Font docs (by clicking on the Font link) tells me that ITALIC is an attribute of Font !! Why won't it compile ?
    Thakns in advance
    H

    The argument to setFont is an instance of the Font class. Therefore, you need to write something like:
    setFont(new Font("Serif", Font.ITALIC, 14));

Maybe you are looking for