views:

376

answers:

1

I try to make it like this : Try using a key listener to detect each time the user enters text into the field. Each time the key event is triggered, get the length() of the text in the JTextField. If the length >= limit, then disable editing. However, if the delete key is pressed, remove the last character in the JTextField and setEditable(true). My problem is how to remove the last character in JTextField? Is this already right? Because it didn't work.Thank's.

Here is some of my code :

public void keyPressed(KeyEvent evt) 
    {
    }
public void keyReleased(KeyEvent evt) 
    {
     int limit = 1;
    JTextField text = (JTextField)evt.getSource();
     if (text.getText().length() >= limit)
        { text.setEditable(false); }
     else
      if(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
       { answer ="";
                    text.setEditable(true);
         }   
    }
public void keyTyped(KeyEvent evt) 
    {
    }
}
A: 

Try wrapping the entire event handler in a SwingUtilities.invokeLater block.

public void keyReleased(KeyEvent evt)  
    { 
        final int limit = 1;
        final int keyCode = evt.getKeyCode();
        final JTextField text = (JTextField)evt.getSource();

        SwingUtilities.invokeLater(new Runnable(){

            public void run() {
                if (text.getText().length() >= limit) 
                { 
                    text.setEditable(false); 
                } 
                else if(keyCode == KeyEvent.VK_BACK_SPACE) 
                {       
                    answer =""; 
                    text.setEditable(true); 
                }
            }
        });                        
    } 

Since event handling and Swing GUI updates are both done on the Event Dispatch Thread, this may be needed to allow the text.getText() method to retrieve all of the entered text.

J2SE31