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));

Similar Messages

  • 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.

  • Formatting a JTextField to a certain length with numbers only.

    Hello,
    What I want to is limit the user to a certain amount of numbers. If the user tries to exceeds the max length, i want it to beep and if they push anything but a number, i want it to beep :O
    I got this to work for limitting the length using documents, but how can i make it so that only numbers are inputted also.
    Thanks!

    I got this to work for limitting the length using documents, but how can i make it so that only numbers are inputted also.If you don't like the way the JFormattedTextField works, then you need to add code to your custom Document make sure each character entered is a valid character. Simply loop through the input String and validate each character individiually.
    Also, the new approach for this kind of customization is to use a DocumentFilter, not override the Document. The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features has an example of this.

  • 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.

  • 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]

  • 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.

  • Date editing in a JTable

    Hello,
    whereas a JFormattedTextField with a mask formatter can be used as editor in a
    JTable just like in a container, a JFormattedTextField with a date formatter
    obviously cannot. The tutorial warns us that table cells are NOT components,
    but in what cases do we have to care?
    I also understand the tutorial in the way that while editing, the editor is
    responsible for displaying the cell, and the cell renderer takes over again
    when editing is stopped. Is that right? If yes, I would not have to care for
    a special renderer, for I'm quite happy with the default one.
    I'm trying to use a JFormattedTextField which would, if working, need only
    little code, for the solutions I found in the net are quite expanded.
    The code below is in many ways defective:
    1) Without renderer
    When editing of the date column starts, the date is displayed in the
    "dow mon dd hh:mm:ss zzz yyyy" form, and doesn't revert even when no edits
    are performed. This doesn't happen if the JFormattedTextField is used
    outside a table.
    2) With renderer
    The value arrives in the renderer sometimes as Object, sometimes as String
    (I suppose the editor is responsible for that.)
    But before I pursue this approach I would like to ask you, whether you
    generally discourge using a JFormattedTextField in a date column.
    If not, please comment my understanding and direct me to a solution.
    import java.awt.*;
    import java.text.*; // ParseException
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*; // MaskFormatter
    import javax.swing.table.*;
    public class FTFTable extends JFrame {
      public FTFTable() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);
        setTitle("FTFTable");
        Container cp = getContentPane();
        String headers[] = {"Date", "Mask: #-##"};
        DateFormat format= new SimpleDateFormat("dd.MM.yyyy");
        DateFormatter df= new DateFormatter(format);
        JFormattedTextField ftfDate= new JFormattedTextField(df);
        MaskFormatter mf1= null;
        try {
          mf1= new MaskFormatter("#-##");
          mf1.setPlaceholderCharacter('_');
        catch (ParseException e) {
          System.out.println(e);
        JFormattedTextField ftf= new JFormattedTextField(mf1);
        final DefaultTableModel dtm= createTableModel(headers);
        dtm.addRow(new Object[]{new java.util.Date(), "1-23"});
        JTable table= new JTable(dtm);
        DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel
    //  Use custom editors
        dcm.getColumn(0).setCellEditor(new DefaultCellEditor(ftfDate));
    //    dcm.getColumn(0).setCellRenderer(new MyDateRenderer());
        dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
        JScrollPane scrollPane = new JScrollPane(table);
        cp.add(scrollPane, BorderLayout.CENTER);
        setVisible(true);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new FTFTable();
      private DefaultTableModel createTableModel(Object[] columnNames) {
        DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
          public Class getColumnClass(int column) {
         Class returnValue;
         if (column>=0 && column<getColumnCount()) {
           returnValue= getValueAt(0, column).getClass();
         else {
           returnValue= Object.class;
         return returnValue;
        return tblModel;
      class MyDateRenderer extends DefaultTableCellRenderer {
        DateFormat format;
        public MyDateRenderer() {
          super();
          format= new SimpleDateFormat("dd.MM.yyyy");
        public void setValue(Object value) {
          if (value instanceof String) System.out.println("Is String");
          if (value instanceof Object) System.out.println("Is Object");
          System.out.println(value);
          System.out.println(format.format(value)); // Crashes if String
          setText((value == null) ? "" : format.format(value));
    }

    Thanks Rob, that was helpful advice.
    If one needs the date displayed only in the form of one's own locale, there's
    no need to implement a cell renderer. Using a JFormattedTextField provides the
    additional facility of using the arrow keys to modify days, months or year.
    import java.awt.*;
    import java.text.*; // ParseException
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.text.*; // MaskFormatter
    import javax.swing.table.*;
    public class FTFTable extends JFrame {
      public FTFTable() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200, 200);
        setTitle("FTFTable");
        Container cp = getContentPane();
        String headers[] = {"Date", "Mask: #-##"};
        MaskFormatter mf1= null;
        try {
          mf1= new MaskFormatter("#-##");
          mf1.setPlaceholderCharacter('_');
        catch (ParseException e) {
          System.out.println(e);
        JFormattedTextField ftf= new JFormattedTextField(mf1);
        DefaultTableModel dtm= createTableModel(headers);
        dtm.addRow(new Object[]{new Date(), "1-23"});
        JTable table= new JTable(dtm);
    //    Locale.setDefault(Locale.FRANCE);
    //  Use custom editors
        table.setDefaultEditor(Date.class, new DateEditorSupply().getEditor());
        DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel();
        dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
        JScrollPane scrollPane = new JScrollPane(table);
        cp.add(scrollPane, BorderLayout.CENTER);
        setVisible(true);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new FTFTable();
      private DefaultTableModel createTableModel(Object[] columnNames) {
        DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
          public Class getColumnClass(int column) {
         Class returnValue;
         if (column>=0 && column<getColumnCount()) {
           returnValue= getValueAt(0, column).getClass();
         else {
           returnValue= Object.class;
         return returnValue;
        return tblModel;
      public class DateEditorSupply {
        DateEditor editor;
        SimpleDateFormat format;
        public DateEditorSupply() {
    //     To be modified according to the locale's default.
    //      this("dd MMM yyyy"); // FRANCE
    //      this("dd.MM.yyyy"); // GERMANY
          this("dd-MMM-yyyy"); // UK
    //      this("MMM d, yyyy"); // US
    //Currently this constructor can only be used with the locale's default pattern.
    // If you need various patterns, you have to implement a cell renderer as well.
        public DateEditorSupply(String pattern) {
          format= new SimpleDateFormat(pattern);
          format.setLenient(false);
          editor= new DateEditor();
        public DefaultCellEditor getEditor() {
          return editor;
        private class DateEditor extends DefaultCellEditor {
          public DateEditor() {
         super(new JFormattedTextField(new DateFormatter(format)));
          @Override
          public Object getCellEditorValue() {
         try {
           java.sql.Date value= new java.sql.Date(format.parse(
                   ((JTextField)getComponent()).getText()).getTime());
           return value;
         catch (ParseException ex) {
           return null;
          @Override
          public Component getTableCellEditorComponent(
              final JTable table, final Object value,
              final boolean isSelected, final int row, final int column) {
         JTextField tf= ((JTextField)getComponent());
         tf.setBorder(new LineBorder(Color.black));
         try {
           tf.setText(format.format(value));
         catch (Exception e) {
           tf.setText("");
         return tf;
          public boolean parseDate(String value) {
         ParsePosition pos= new ParsePosition(0);
         format.parse(value, pos); // updates pos.
         if (pos.getIndex()!=value.length() ||
             format.getCalendar().get(Calendar.YEAR)>2500) return false;
         return true;
          @Override
          public boolean stopCellEditing() {
         String value = ((JTextField)getComponent()).getText();
         if (!value.equals("")) {
    /*       This code would accept alphabetic characters within or at the end of
    //       the year in a dd.MM.yyyy pattern, as well as more than 4-digits in the
    //       year string.
           try {
             format.parse(value);
           catch (ParseException e) {
             ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
             return false;
           We avoid this in using "parseDate(value)" instead.
           if (!parseDate(value)) {
             ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
             return false;
         return super.stopCellEditing();
        } // end DateEditor
    }Thanks to André for sharing his .
    Edited by: Joerg22 on 03.07.2010 14:11
    I made some changes to the DateEditorSupply class, so that the code can easily be used when storing the table date in a database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Alternative to MaskFormatter ?

    I use JDK 1.3 and I would like to format a JTextField like with a MaskFormatter. But JFormatterText and MaskFormatter aren't available in JDK 1.3.
    Does anyone know an alternative ?

    Well, there is Soho Organizer, $99.00, contacts, calendars, tasks and notes. iCloud compatible (most other things as well, except for MS Exchange)
    But iCal and Address Book do 95% of what Soho does.

  • TODAY in textfield!!!

    how can I input the current date in a JTextField?
    A snippet would be most welcome!!!
    thanks!

    import java.util.Date;          
    import java.text.DateFormat;
    Date today;
    String dateOut;
    today = new Date();
    dateOut = DateFormat.getDateInstance().format(today);   
    JTextField textfield = new JTextField(dateOut);

  • 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.

  • 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) ?

  • 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)

  • 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);}
    }

Maybe you are looking for