根据按下按钮的时间从JTextField中清除元素

时间:2019-02-06 23:56:24

标签: java swing jbutton jtextfield event-dispatch-thread

任务是编写一个程序,其中用户键入一个非常大的数字,然后当他按下“清除”按钮时,文本字段应该清除,但不是全部。需要先删除一个字符,然后再增加按下“清除”按钮的时间,要清除的字符数应增加。

我写了这段代码,但是似乎没有用。它实际上什么也没做。

bm.addChangeListener( new ChangeListener() {    //added the changeListener to 
    @Override                                    // buttonmodel
    public void stateChanged(ChangeEvent e) {
        if ( bm.isPressed() && !isStarted ){
            start = System.nanoTime();
            isStarted = true;
        }

        //while button is pressed, calculate the time it has been pressed         
        //then update text of textfield

        while  ( bm.isPressed() && isStarted ){
            long timeElapsed = System.nanoTime() - start;
            if ( !resultField.getText().isEmpty()){
                int length = resultField.getText().length();
                String resultS = resultField.getText();                    
                if ( timeElapsed == 1 && length > 1 ){                       
                    resultField.setText(resultS.substring(0, length-1));
                } else if ( timeElapsed == 2 && length > 2){
                    resultField.setText(resultS.substring(0,length-2));
                } else if ( timeElapsed == 3 && length > 3){
                    resultField.setText(resultS.substring(0,length-3));
                } else if ( timeElapsed > 4 && length > 4){
                    resultField.setText(resultS.substring(0, length-4 ));
                } 
            }
        }
    }
});

0 个答案:

没有答案