javascriptjavajqueryjtextareacharactercount

Running character countdown in java?


I can find plenty of Jquery/javascript examples but how is it done in java?

i.e http://jsfiddle.net/timur/47a7A/

$(document).ready(function() {
    var text_max = 99;
    $('#textarea_feedback').html(text_max + ' characters remaining');

$('#textarea').keyup(function() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
    });
});

I've got (64)min/max(256) character input validation on an existing JTextArea but I'd also like a running character countdown to display beneath the textbox like on twitter or what not. No idea how to convert the above to strictly java, if at all ideal.


Solution

  • Use KeyListeners:

    private int max_chrs = 256;
    
    textarea.addKeyListener(new KeyListener(){
        @Override
        public void keyPressed(KeyEvent e){
             if(textarea.getText().length() >= this.max_chrs){
                 e.consume();
             }
        }
    
        @Override
        public void keyTyped(KeyEvent e) {
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
             label.setText( Integer.toString(this.max_chrs - textarea.getText().length()) );
        }
    });