1

每次用户在字段中输入文本时,我都想使用关键侦听器进行检测。每次触发关键事件时,我都想length()获取JTextField. 如果length >= limit然后我想禁用编辑。但是,如果按下删除键,我想删除and中的最后一个字符JTextFieldsetEditable(true)

如何删除 中的最后一个字符JTextField

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) {}

}

4

1 回答 1

1

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.

于 2010-05-12T15:34:11.480 回答