MaskFormatter problem

I am using JFormattedTextFields on most of my form input fields. Not sure if this is the correct way to do this as I'm new but I created a MaskFormatters class that contains all of my MaskFormatters all in one place.
i.e.
public final MaskFormatter FIFTEEN_DIGITS = new MaskFormatter("###############);
Then on my forms I create:
jftfMSISDN = new JFormattedTextField(mask.FIFTEEN_DIGITS);
The problem I'm having is when using a formatter the 'text' is not commited to the 'value' when focus leaves the field unless the whole mask is filled in. What I really want is a mask that will allow 0-15 numbers - not just 15 only. Is there a way to set the mask to commit even if the mask is not completely filled out? I tried FIFTEEN_DIGITS.setPlaceHolderCharacter(' ') and it still does not commit the value. Although I tried again with FIFTEEN_DIGITS.setPlaceHolderCharacter('5') and it completed the field with all 5's and commited as expected.
TIA

import java.awt.*;
import java.text.*;
import javax.swing.*;
public class FormatTest {
  public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumIntegerDigits(15);
    nf.setMinimumIntegerDigits(1);
    nf.setGroupingUsed(false);
    JFormattedTextField ftf = new JFormattedTextField(nf);
    ftf.setPreferredSize(new Dimension(125, ftf.getPreferredSize().height));
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weighty = 1.0;
    gbc.gridwidth = gbc.REMAINDER;
    panel.add(ftf, gbc);
    JTextField tf = new JTextField(8);
    panel.add(tf, gbc);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.setSize(200,130);
    f.setLocation(400,300);
    f.setVisible(true);
}This will commit the last 15 digits in the ftf. If you want to limit the number of digits entered into the ftf to 15, the next step is a document filter. Also, note the behavior when a decimal is entered.

Similar Messages

  • Problems with MaskFormatter and JFormattedTextfield

    Hi,
    I'm new to the forum and Java programming so if anyone is willing to answer this query with a small degree of patience I would be immensely, humbly grateful!
    I'll say firstly that I wrote the program in jdk1.4.2 then recompiled it in 1.6.0 in the vain hope that the problem would go a way, but no such luck.
    Right, I'm using one Formatted textfield with a MaskFormatter on which I change the mask according to what information I want from the user:
    class myFormatter extends MaskFormatter {
              String key;
              public void setMask(String k){
                   key = k;     
                   if (key.equals("text")) {
                        try{
                             super.setMask("*************"); // for text, eg star names
                             super.setValidCharacters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("num")) {
                        try{
                        super.setMask("****#"); // for numbers 1-10000 eg frame num
                                    super.setValidCharacters("0123456789\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("epoch")) try{
                        super.setMask("####.#"); // for epoch
                        super.setValueContainsLiteralCharacters(true);
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("yna")) try{
                        super.setMask("L"); // for single lower case characters eg y/n/a
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("coord")) try{
                        super.setMask("*## ## ##"); // for RA/Dec
                        super.setValueContainsLiteralCharacters(true);
                        super.setValidCharacters("0123456789+-\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("reset")) try{
                        super.setMask("*********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else  try{
                        super.setMask("********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
    -----------------------------------------------------------------------------------------------------Ok, now I've only gotten as far as checking the implementation of the "epoch", "text", "yna" and "coord" keys. I've discovered two main problems:
    1. The A, ? and H masks in MaskFormatter just simply did not work; the textfield would not let me enter anything, even when setting the valid the characters, hence having to use * for implementing the "text" key.     
    But most importantly:
    2. The "coord" mask will not let me enter anything (example coordinates -32 44 55) and when I try (in particular press the backspace to start entering at the beginning of the ttextfield instead of the middle, where the cursor is put) I presented with this horrendous complaint from the compiler:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.text.MaskFormatter.isLiteral(MaskFormatter.java:566)
    at javax.swing.text.MaskFormatter.canReplace(MaskFormatter.java:711)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:560)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:533)
    at javax.swing.text.DefaultFormatter$DefaultDocumentFilter.remove(DefaultFormatter.java:711)
    at javax.swing.text.AbstractDocument.remove(AbstractDocument.java:573)
    at javax.swing.text.DefaultEditorKit$DeletePrevCharAction.actionPerformed(DefaultEditorKit.java:1045)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2844)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2879)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2807)
    at java.awt.Component.processEvent(Component.java:5815)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:693)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:958)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:830)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:657)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    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)
    A NullPointerException??? I even tried priming the textfield by setting the value using formatTxt.setValue(format.stringToValue("+00 00 00")).
    Does anyone have any ideas on this error (or how I can get around this without delving to much into other filtering classes)? Has anyone had similar problems with the MaskFormatter masks not accepting what they claim they do (I looked through the posts on the subject).
    Thanking you in advance for you patience........

    Hi,
    Thank you very much for your prompt reply.
    I've done as you said - written a smaller program to test each mask. They don't work quite as I expected but you're right, each mask works fine, its changing the masks that's the problem. I wrote this to test it out:
    public class testMask {
    //Note:      main() won't let u access object/variable methods if declared here
    // GUI items to be globally accsessed:
         JFrame MainWin;
         JPanel panel, panel1;
         JLabel question, answer;
         JButton send, askQues, change;
         JFormattedTextField formatTxt;
         myFormatter format;
    // I/O to be globally accessed:
         String usrinput = null;
         public static void main( String[] args ) {
              testMask GUI = new testMask();
         public testMask(){
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public synchronized void run() {
                              create();
                 });                              //     thread safe code to make sure that UI painting is not interrupted by events, possibly causing the UI to hang
         public synchronized void create(){
              //set look and feel of GUI
              try {
              } catch (Exception e) {
                             System.out.println("Error - Problem displaying window");
              //initialise main window and set layout manager
              MainWin = new JFrame("Test Masks");     
              MainWin.getContentPane().setLayout(new BorderLayout());     
              // initialise containers to go on MainWin
              panel = createPanel();
              MainWin.getContentPane().add(panel, BorderLayout.CENTER);
              MainWin.pack();
              MainWin.setSize(300,150);
              MainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              MainWin.setLocation(150, 150);
              MainWin.setVisible(true);
         public synchronized JPanel createPanel() {
              JPanel panel1 = new JPanel();
              panel1.setLayout(new GridLayout(3,1));
              Border border = BorderFactory.createEtchedBorder();
              panel1.setBorder(BorderFactory.createTitledBorder(border, " Test Panel "));
              question = new JLabel("Please enter drive");
              answer = new JLabel();
              answer.setBorder(border);
              panel1.add(question);
              JPanel pane1 = new JPanel(new FlowLayout());
    //------Set up formatted textfield for user input to be verified--------
              format = createFormatter();
              format.setMask("drive");
              formatTxt = new JFormattedTextField(format);
              formatTxt.setColumns(10);
              send = new JButton(" Send ");
              send.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              send.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        try{
                             formatTxt.commitEdit();
                        } catch (java.text.ParseException exc) {
                             answer.setText("Problem with formatting: " + exc.getMessage());
                             return;
                        SwingUtilities.invokeLater(new Runnable() {
                             public synchronized void run() {                         
                                  if (formatTxt.isEditValid()) {
                                       usrinput = formatTxt.getText();
                                       answer.setText(usrinput);
                                  } else { answer.setText("Input not of valid format"); }
              change = new JButton("Change mask");
              change.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              change.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        question.setText("Please enter coord in format ## ## ##");
                        format.setMask("coord");
              pane1.add(formatTxt);
              pane1.add(send);
              pane1.add(change);
              panel1.add(pane1);
              panel1.add(answer);
              return panel1;
         protected myFormatter createFormatter() {
              myFormatter formatter = new myFormatter();
              return formatter;
    class myFormatter extends MaskFormatter {
         String key;
         public void setMask(String k){
              key = k;     
              if (key.equals("coord")) {
                   try{
                        super.setMask("*## ## ##"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else if (key.equals("drive")) {
                   try{
                        super.setMask("L:"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else  {
                   try{
                        super.setMask("********************"); // accept anything
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
    }When I click on the "change" button, the textfield won't let me enter anything in, no matter what I change the mask from or to.
    Does anyone have any idea how I can implement the mask change dynamically? The only thing I could think of was to somehow re-initalise the textfield then do a repaint, but I don't know how or if that would even work.
    Thanking you again in anticipation,
    Mellony

  • JFormattedTextField - verfiier problem

    I have a problem using JFormattedTextField for data entry,
    (see _postcodeTextField below ).
    Specifiying a MaskFormatter does restirct the data accepted, in this case to 4 numbers.
    My problem lies with the InputVerifier.
    When I shift the focus (using the <TAB> key) the verifier is invoked. If the
    input is invalid (e.g. 356 which consists of 3 numbers not 4) then as expected
    there is a Beep and a message dialog appears.
    Once the dialog is closed, the focus returns to the _postcodeTextField as expected.
    However, if I then enter a number, it does not appear, but if I enter the number again,
    it appears.
    Why is the first number lost?
    This code has been derived from examples found on the Sun site.
    Curiously there is mention of "focus-transfer problems" with the verifier.
    I like the ability to define an input mask to restirct data entry, but I am
    disappointed by the problems I have encountered in verification.
    I have tried a FocusHandler (extends FocusAdapter) but this also has problems.
    The new JFormattedTextField looks capable of providing the functionality I require,
    but it appears to have its quirks and will need a patch in time.
    Meanwhile, any suggestions?
    _postcodeTextField = getTextFieldWithFormat("####");
    _postcodeTextField.setToolTipText("4 digit code e.g. 4065");
    private JFormattedTextField getTextFieldWithFormat( String format )
    MaskFormatter formatter = null;
    try
    formatter = new MaskFormatter(format);
    catch (java.text.ParseException exc)
    System.err.println("formatter is bad: " + exc.getMessage());
    JFormattedTextField ftf = new JFormattedTextField(formatter);          
    ftf.setFont( new Font( "Arial", Font.PLAIN, 14 ) );
    ftf.setColumns(format.length());      
    ftf.setInputVerifier(new FormattedTextFieldVerifier());
    return ftf;     
    } // getTextFieldWithFormat()
    public class FormattedTextFieldVerifier extends InputVerifier
    public class FormattedTextFieldVerifier extends InputVerifier
    public boolean verify(JComponent input)
    if (input instanceof JFormattedTextField)
    JFormattedTextField ftf = (JFormattedTextField) input;
    try
    ftf.commitEdit();
    catch (ParseException pe )
    return false;
    return true;               
    } // verify()          
    public boolean shouldYieldFocus(JComponent input)
    boolean inputOK = verify(input);
    if (!inputOK)
    //Avoid possible focus-transfer problems when bringing up
    //the dialog by temporarily removing the input verifier.
    //This is a workaround for bug #4532517.
    input.setInputVerifier(null);
    Toolkit.getDefaultToolkit().beep();
    //Display a warning message.
    String message = "Please try again.";
    JOptionPane.showMessageDialog(null, message,
    "Invalid Value", JOptionPane.WARNING_MESSAGE);
    //Reinstall the input verifier.
    input.setInputVerifier(this);
    return inputOK;
    } // shouldYieldFocus()
    } // FormattedTextFieldVerifier class

    (this could be a duplicate post
    first reply disappeared into the ether)
    Meanwhile I consider you have earnt the 10 Duke points I attached to the\is topic.
    I imagine I have to award them to you or something? How do I do that?I don't really know, but keep them for when someone spends a fair bit of
    time and effort solving a problem for you.
    In this case it was just a matter of testing the code and reporting the result.
    Thanks for the offer.

  • More problem with JFormattedTextField

    Here is the code where I want size and input validation for JFormattedTextField
    MaskFormatter f10=new MaskFormatter("***************");
    f10.setValidCharacters("0123456789");
    t4= new JFormattedTextField(f10);
    It's behaving in funny way. It allows me only specfied no of characters(15 here) and only nos. But after entering nos and when it changes the focus, the entered data is disappearing. What could be the problem?

    Interesting Problem,
    Watching for result.

  • PostCode - problem with validation

    Hello,
    I have problem with codes in Netbeans.I Have two code.
    The first is to mask formatter and i put in on Post int code
    try
    MaskFormatter PostCode = new MaskFormatter("##-###");
    PostCode.setValidCharacters("0123456789");
    RegisterPostCode = new JFormattedTextField(PostCode);
    catch (ParseException e) {
    }The Second check, the RegisterPostCode is not null
    class Steps implements ActionListener{
       int step = 0;  
          public void actionPerformed(ActionEvent e) {
          if (step == 0){
    String NotEmptyPostCode = RegisterPostCode.getText();
             if(NotEmptyPostCode == null || NotEmptyPostCode.length() == 0) {
       jLabel4.setText("This Field is empty");
             return;
    step++;
          }Problem is the second code doesnt work and I dont now how to create code to check the JFormatterField is compatible with the first code
    Please help.

    Hi! I have an HTML region and on my "before header process" I fetch only one record (the data is got from a package I've created on the DB).
    This region has a few items and when I press the save button (I created on the screen) the value of all the items are cleared if the validation ocurrs, I don't know why, is this because the page doesn;t perfom again my "before header process"?
    Thanks!

  • Problem with a mask in a JFormattedTextField

    I am tring to create a text box with a mask.
    This object text box is declared like a class var.
    I have another object, a mask object that is also declared as a class var
    but I cant create this mask. The errors are commented,
    if you erase the comments and create the class you are going to see the error.
    javac ContraBase.java
    java ContraBase
    Estoy tratando de crear un campo de texto con mascara.
    este objeto texto esta definico como variable de clase
    tengo definida una mascara tambien como variable de clase
    Pero no me deja crear la mascara. Los errores estan comentados,
    si quita los comentados y crea el class vera el problema.
    javac ContraBase.java
    java ContraBase
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.JFormattedTextField;
    class ContraBase extends JPanel
         //MaskFormatter mascara1 = new MaskFormatter("########"); //aca se produce un error
         //JFormattedTextField PRECIOA = new JFormattedTextField (mascara1); //la idea es definir aca la mascara
         JFormattedTextField PRECIOA = new JFormattedTextField ("########");
         public ContraBase()
              //TEXTBOX
              PRECIOA.setToolTipText("PRECIOA");
              add(PRECIOA);
         static public void main (String[] args)
              System.out.println("Iniciando programa.");
              try
                   JFrame VentanaPrincipal = new JFrame("Practicas con Java, trabaja con Base");
                   VentanaPrincipal .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   VentanaPrincipal .getContentPane().add(new ContraBase(), BorderLayout.CENTER);
                   VentanaPrincipal .setSize(350,500);
                   VentanaPrincipal .setVisible(true);
              catch(Exception e)
                   System.out.println("****INGRESA A EXCEPTION main****");
                   System.out.println(e.toString());
                   System.out.println("****SALE DE EXCEPTION main****");
                   return;
              System.out.println("Creacion Finalizada.");
    }

    Sounds like that field is editable. The renderer renders the display when a field is not
    being edited, a TableCellEditor is in charge when the field is edited, and the default
    editor is just a JTextField.
    : jay

  • How to make SimpleDateFormat behave like MaskFormatter

    Hi!
    I'm using a JFormattedTextField to input date values.
    I defined it like this:
    jftfDate = new JFormattedTextField( new SimpleDateFormat("yyyy/MM/dd") );
    It works as expected but it doesn't give the user any feedback of the date format as he types it.
    If I used the MaskFormatter insted like:
    mf1 = new MaskFormatter("####/##/##");
    mf1.setPlaceholderCharacter('_');
    jftfDate = new JFormattedTextField( mf1 );
    It would give the user feedback but wouldn't validate the numbers. For example, I could have a month with the number 13.
    Does anyone had the same request and knows the answer to or have any clues?
    Thanks,
    Eduardo

    check out the link shown below and see if it solves your problem:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=312875
    ;o)
    V.V.

  • Problem with the keylistener

    Hi ,
    I am strucking with keylistener problem. I need the date in yyyy/mm/dd and no other letter it should allow me that means 2008/12/21.(i .e.,only digits and / at 5 and 8 postion) and the total length of the field is not more than 10.
    i have done to accept only digits and max length of the date field is 10 by using the below code but unable valide / at chart 5 and 8 position.
    Seek urgent help and reply would greately be appreciated.
    public class DateListener extends JTextField implements KeyListener
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public void keyTyped(KeyEvent e)
              final char c = e.getKeyChar();
              System.out.println("this.getText() value is" +this.getText());
              if( this.getText().length()> 9)
                   e.consume();
              System.out.println(this.getCaretPosition());
              if((c < '0' || c > '9') )
                   e.consume();
              }else if(this.getText().length() < 4 && this.getText().length() > 5 && c != '/' )
                   e.consume();
    Thank you,

    Hi, I struk with Maskformatter. I am validating the date entered my user. I have made the date using
    mft = new MaskFormatter("####/##/##");
    mft.setPlaceholderCharacter('_');
    activeDateTF = new avax.swing.JFormattedTextField(mft); where activeDateTF is a format text field . I have added the keylistener to that
    DateListener dateListener = new DateListener();
    this.activeDateTF.addKeyListener(dateListener);
    and datelistener has the following.
    public void keyReleased(KeyEvent e)
    { // TODO Auto-generated method stub
    System.out.println("you are in key released");
    final char c = e.getKeyChar();
    if(c!='\b') {
    al.add(c);
    JTextField ft =(JTextField)
    e.getSource(); if(al.size()== 8 )
    { System.out.println("ft.text value is " +ft.getText());
    al.clear();
    } where al is a arraylist used to know how many digits have been entered by user since the date contains only 8 (2008/12/12) excluding /. But the validations are becoming very difficult since the user may just enter 2008 and leave. my question is how do i get the value without _(placeholder) from the formatted text filed and how to validate the digits entered by user. Plesae help srini

  • MaskFormatter stops allowing input

    i need a MaskFormatter which allows the user ot input time in the format hh:mm. features:
    user should be able to conveniently type four digites without having to press the ":" key
    the value of the JFormattedTextfield should always be of type date, never string
    the problem: once i set a value, the textfield doesn't allow input anymore. here's an example:
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.JButton;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.text.MaskFormatter;
    public class TimeFormatter extends MaskFormatter {
         // set mask and placeholder
         public TimeFormatter() {
              try {
                   setMask("##:##");
                   setPlaceholderCharacter('0');
                   setAllowsInvalid(false);
                   setOverwriteMode(true);
              } catch (ParseException e) {
                   e.printStackTrace();
         @Override
         public Object stringToValue(String string) throws ParseException {
              SimpleDateFormat df = new SimpleDateFormat("HH:mm");
              if( string == null)
                   string = "00:00";
              return df.parse(string);
         @Override
         public String valueToString(Object value) throws ParseException {
              SimpleDateFormat df = new SimpleDateFormat("HH:mm");
              if( value == null)
                   value = new Date( 0);
              return df.format( (Date) value);
         public static void main(String[] args) throws Exception {
              // textfield 1: create formatter and textfield
              final MaskFormatter formatter = new TimeFormatter();
    //          formatter.setValueClass(java.util.Date.class);
              final JFormattedTextField tf1 = new JFormattedTextField( formatter);
              tf1.setPreferredSize( new Dimension( 50, 22));
              // set initial value
              tf1.setValue( new Date());
              // textfield 2: create formatter and textfield
              final JFormattedTextField tf2 = new JFormattedTextField( formatter);
              tf1.setPreferredSize( new Dimension( 50, 22));
              // no initial value
              // tf1.setValue( new Date());
              // button to show current value
              JButton bt = new JButton("Show Value");
              bt.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.out.println("value 1 = " + tf1.getValue() + ", value 2 = " + tf2.getValue());
                        System.out.println("value 1 = " + tf1.getText() + ", value 2 = " + tf2.getText());
                        // System.out.println("value class: " + formatter.getValueClass());
              // main frame
              JFrame f = new JFrame();
              f.getContentPane().setLayout(new FlowLayout());
              f.getContentPane().add(tf1);
              f.getContentPane().add(tf2);
              f.getContentPane().add(bt);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.pack();
              f.setSize(300, 100);
              f.setVisible(true);
    }you see, that you can't edit the first textfield. it has a value set (current date). however, you can edit the 2nd textfield, but once that field loses the focus, you can't edit that anymore either.
    does anyone know what's happening and have a solution?

    you can lock this, i've solved it.
    however, since probably more people will run into this issue, here's a quick solution:
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.JButton;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.text.MaskFormatter;
    public class TimeFormatter extends MaskFormatter {
         // set mask and placeholder
         public TimeFormatter() {
              try {
                   setMask("##:##");
                   setPlaceholderCharacter('0');
                   setAllowsInvalid(false);
                   setOverwriteMode(true);
              } catch (ParseException e) {
                   e.printStackTrace();
         @Override
         public Object stringToValue(String string) throws ParseException {
              return new MyDate( string);
         @Override
         public String valueToString(Object value) throws ParseException {
              if( value == null)
                   return new MyDate().toString();
              return ((MyDate) value).toString();
         public static void main(String[] args) throws Exception {
              // textfield 1: create formatter and textfield
              final MaskFormatter formatter = new TimeFormatter();
              final JFormattedTextField tf1 = new JFormattedTextField( formatter);
              tf1.setPreferredSize( new Dimension( 50, 22));
              // set initial value
              tf1.setValue( new MyDate());
              // textfield 2: create formatter and textfield
              final JFormattedTextField tf2 = new JFormattedTextField( formatter);
              tf1.setPreferredSize( new Dimension( 50, 22));
              // no initial value
              // tf1.setValue( new Date());
              // button to show current value
              JButton bt = new JButton("Show Value");
              bt.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.out.println("value 1 = " + tf1.getValue() + ", value 2 = " + tf2.getValue());
                        System.out.println("value 1 = " + tf1.getText() + ", value 2 = " + tf2.getText());
                        // System.out.println("value class: " + formatter.getValueClass());
              // main frame
              JFrame f = new JFrame();
              f.getContentPane().setLayout(new FlowLayout());
              f.getContentPane().add(tf1);
              f.getContentPane().add(tf2);
              f.getContentPane().add(bt);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.pack();
              f.setSize(300, 100);
              f.setVisible(true);
         public static class MyDate extends Date {
              public MyDate() {
                   super();
              public MyDate( String time) {
                   super();
                   try {
                        setTime( new SimpleDateFormat("HH:mm").parse(time).getTime());
                   } catch (ParseException e) {
                        e.printStackTrace();
                        setTime( 0);
              @Override
              public String toString() {
                   SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                   return df.format( getTime());
    }the problem: you mustn't use Date as an object of the formatter.
    the reason: Date doesn't have a constructor that allows a string specified in "HH:mm" format. new Date("00:00") throws an
    IllegalArgumentException()
    in Date's
    public static long parse(String s)
    During text input the parser is called from Date's String parameterized constructor:
    MaskFormatter's stringToValue(String value, boolean completeMatch)
    calls
    DefaultFormatter's stringToValue(String string)
    which contains:
    cons = vc.getConstructor(new Class[] { String.class });
    return cons.newInstance(new Object[] { string });
    and the instantiation of Date( "00:00") fails because the above mentioned IllegalArgumentException()
    In short: a given MUST for the MaskFormatter is, that the used object must have a valid constructor which allows a String parameter.

  • MaskFormatter with variable length

    I'm trying to create a MaskFormatter with the following mask:
    "AAAA AAAA AAAA AAAA"
    The user should be able to enter whatever he likes as long as it is automatically formatted with a space between each group.
    Valid combinations are:
    1234 45
    12
    FF12 5454 546
    etc...
    Further on, small letters should be converted to Uppercase when typing. How do I do this?
    I have already tried to write a custom VariableMaskFormatter as described in (http://forum.java.sun.com/thread.jspa?forumID=57&threadID=461577&start=3)
    but I doesn't work as expected.
    It only works if the placeholdercharacter which is used is also an allowed charachter when typing. But I don't want to make the space character an allowed character.
    How can this be solved?
    Thanks
    Fabian

    Thank you. I have been able to create a custom MaskFormatter which will dynamically adapt the mask based on what was entered.
    But I still have two open issues:
    1. How can I do so that all smaller letters are converted to captital letters when typing? Normally you would use the letter "U" in the mask, but, users should be able to enter a alphanumeric character, so I use "A" instead.
    2. Cursor problem:
    - How can I make delete and backspace button act as if it was in a notepad? If I press delete, charachters at the right from the cursor should be deleted and the cursor should not move forward.
    Please find below some code samples.
    package test.component;
    import java.text.ParseException;
    import javax.swing.text.MaskFormatter;
    public class VariableLengthMaskFormatter extends MaskFormatter {
        public VariableLengthMaskFormatter() {
            super();
        public VariableLengthMaskFormatter(String mask) throws ParseException {
            super( mask );
         * Override the setMask method
        public void setMask(String mask) throws ParseException {
            super.setMask(mask);
         * Update our blank representation whenever the mask is updated.
        public void setPlaceholderCharacter(char placeholder) {
          super.setPlaceholderCharacter(placeholder);
        /* (non-Javadoc)
         * @see javax.swing.text.MaskFormatter#stringToValue(java.lang.String)
        public Object stringToValue( String value ) throws ParseException {
            Object rv;
            // Get the mask
            String mask = getMask();
            if ( mask != null ) {
                // Change the mask based upon the string passed in
                setMask( getMaskForString( mask, value ) );
                // Using the substring of the given string up to the mask length,
                // convert it to an object
                rv = super.stringToValue( value.substring( 0, getMask().length() ) );
                // Change mask back to original mask
                setMask( mask );
            } else
                rv = super.stringToValue( value );
            // Return converted value
            return rv;
         * Answer what the mask should be for the given string based on the
         * given mask. This mask is just the subset of the given mask up to
         * the length of the given string or where the first placeholder
         * character occurs in the given string. The underlying assumption
         * here is that the given string is simply the text from the
         * formatted field upon which we are installed.
         * @param value The string for which to determine the mask
         * @return A mask appropriate for the given string
        protected String getMaskForString( String mask, String value ) {
            StringBuffer sb = new StringBuffer();
            int maskLength = mask.length();
            char placeHolder = getPlaceholderCharacter();
            for (int k = 0, size = value.length(); k < size && k < maskLength ; k++) {
                if ( placeHolder == value.charAt( k ) ) {
                    //break;
                    sb.append(' ');               
                } else {
                    sb.append( mask.charAt( k ) );
            return sb.toString();
             MaskFormatter theRekFormat = null;
             try {
                 theRekFormat = new VariableLengthMaskFormatter( "AAAA AAAA AAAA AAAA" );
                 theRekFormat.setPlaceholderCharacter(' ');
                 theRekFormat.setValueContainsLiteralCharacters( false);
             } catch (Exception ex) {
                 System.out.println(ex.toString());
             JFormattedTextField myMaskAccount = new JFormattedTextField(theRekFormat);
              myMaskAccount.addKeyListener(new KeyAdapter(){
                            public void keyReleased(KeyEvent ke){
                              if(ke.getKeyCode() == KeyEvent.VK_DELETE) {
                                  myMaskAccount.setCaretPosition(myMaskAccount.getCaretPosition()-1);
                              } else {
                                  System.out.println("listening to key: " + ke.getKeyCode());
                              }}});

  • Focus Problem (Java 6)

    Hallo guys,
    I am sorry that I cannot provide a running application but just a method. What I wanted to do is to compare two formatted text field and if they don't have valid values it throws a JOptionPane. My problem is that I see this Joptionpane at least 3-4 times. Can anyone help me? Actually as I debugged it, I saw that whenever I lose the focus from the first component, it doesn't only run the focus event of the first component, but it also runs the focus events of the second component. That's what I actually DON'T want to have. If anyone can help me I will be glad.
    private void initValues(String value) {
            MaskFormatter mask = new MaskFormatter();
            mask.setValidCharacters("0123456789");
            componentFrom.setFormatterFactory(new DefaultFormatterFactory(new RangeNumberFormatter(new Integer(0),
                    new Integer(999999),
                    new DecimalFormat("######"))));
            componentTo.setFormatterFactory(new DefaultFormatterFactory(new RangeNumberFormatter(new Integer(0),
                    new Integer(999999),
                    new DecimalFormat("######"))));
            getContentPanel().setLayout(gridBagLayout);
            getContentPanel().add(new JLabel(" " + res.getString("DynamicFromTo.from")), new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(componentFrom, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(new JLabel(res.getString("DynamicFromTo.to")), new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(componentTo, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5), 0, 0));
            getContentPanel().add(new JLabel(value), new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
            componentFrom.addFocusListener(new FocusListener() {
                public void focusGained(FocusEvent e) {
                    if (componentFrom.getText().equals("") && componentTo.getText().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                public void focusLost(FocusEvent e) {
                    StringBuffer temp = new StringBuffer(componentFrom.getText());
                    componentFrom.setText(temp.toString());
                    if (!e.isTemporary()) {
                        if (!isNumeric(componentFrom.getText())) {
                            componentFrom.setText(componentFrom.getText());
                        } else {
                            String fromStr = ((JTextField) (e.getSource())).getText();
                            String fromStr2 = fromStr.replace(',', '.');
                            String toStr = componentTo.getText().trim();
                            String toStr2 = toStr.replace(',', '.');
                            if (!fromStr2.equals("") && (!toStr2.equals("")) && isNumeric(toStr2) && isNumeric(fromStr2)) {
                                double to = Double.parseDouble(toStr2);
                                double from = Double.parseDouble(fromStr2);
                                if (from > to) {
                                    JOptionPane.showMessageDialog(null, res.getString("DynamicFromTo.error"));
                                   componentFrom.requestFocus();
            componentTo.addFocusListener(new FocusAdapter() {
                public void focusGained(FocusEvent e) {
                    if (componentFrom.getText().equals("") && componentTo.getText().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                public void focusLost(FocusEvent e) {
                    StringBuffer temp = new StringBuffer(componentTo.getText());
                    componentTo.setText(temp.toString());
                    if (((JTextField) (e.getSource())).getText().trim().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                    String toStr = ((JTextField) (e.getSource())).getText();
                    String toStr2 = toStr.replace(',', '.');
                    String fromStr = componentFrom.getText().trim();
                    String fromStr2 = fromStr.replace(',', '.');
                    if (!toStr2.equals("") && (!fromStr2.equals("")) && isNumeric(toStr2) && isNumeric(fromStr2)) {
                        double to = Double.parseDouble(toStr2);
                        double from = Double.parseDouble(fromStr2);
                        if (from > to) {
                            JOptionPane.showMessageDialog(null, res.getString("DynamicFromTo.error"));
            componentFrom.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if ((componentFrom.getText() + ((JTextField) e.getComponent()).getText()).length() == 0) {
                        if (componentTo.getText().trim().equals("")) {
                            if (isCommentable()) {
                                comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
            componentTo.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if ((componentFrom.getText() + ((JTextField) e.getComponent()).getText()).length() == 0) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
            components.add(componentFrom);
            components.add(componentTo);
            registerComponent(componentFrom);
            registerComponent(componentTo);
        }Edited by: NEO1976 on Sep 5, 2008 10:04 AM

    I am sorry that I cannot provide a running application but just a method.Well then sorry that I cannot provide an aswer, just a sarcastic response.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Help me to change the maskformatter I have written to my new requirement

    how to create a MaskFormatter which accepts 1 to 3 digits followed by a dot(.)
    then again 1 to 3 digits followed by a dot(.)
    then again 1 to 3 digits followed by a dot(.)
    then again 1 to 3 digits.
    Its for creating IP Address input acceptance field in java.
    I have made one like below.
    private MaskFormatter getMf1() {
              if (mf1 == null) {
                   try{
                   //mf1 = new MaskFormatter("   ###  .   ###  .   ###  .   ### ");
                        mf1 = new MaskFormatter("***.***.***.***");
                        mf1.setValidCharacters(" 0123456789");
                   //mf1.setValueContainsLiteralCharacters(false);
                   }catch(Exception e){e.printStackTrace();}
              return mf1;
         }Here attmost we can have atmost 3 digits before or after those dots.
    Please modify this code to exactly suite to my requirement.
    The text field should not accept whitespace.
    Please any one worked on this, reply here.

    A brief read of the MaskFormatter API documentation doesn't suggest any way to use this class to do what you want. And the comment there that "The mask is on a per character basis" doesn't look good if you a variable (but still restricted) number of characters.
    You can try with a Keylistener.The problem with a KeyListener is that the input gesture may not be associated with any keyboard activity (eg the mouse might have been used, or the text might be being set programatically) or the keyboard activity might not be so straight foward (eg Ctrl+V).
    You could obtain the document associated with the text field and work with that.
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html
    (and the pages it links to)
    Or you could write your own subclass of javax.swing.text.DefaultFormatter with a DocumentFilter and NavigationFilter that implement the logic you want.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

Maybe you are looking for