javaswingjtextfieldfocuslistener

How to set different Limit in JTextField for showing Input Hint and Input


I want to make a custom JTextField, and my requirements are:

  1. Show Hint in Text Field.
  2. It will take a limited number of characters.

Both the requirements are working. But the problem is that if I set the limit to 6, then it sets the input length to 6. I need to set an additional limit.

Like, Input Hint limit: 20, Number Input Limit: 6 Example: Input Hint: Enter a Number Here, Input: 666666 (Maximum 6 digit).

Here are both of the class.

CustomTextField.java

public class CustomTextField extends JTextField implements KeyListener, FocusListener{
    private static final long serialVersionUID = 1L;

    private final int CHAR_LIMIT = 6;
    private String hint = null;
    private boolean showingHint;

    public CustomTextField(String hint) {
        super(hint);
        this.hint = hint;
        this.showingHint = true;
        this.setDocument(new CustomJTextFieldCharLimit(CHAR_LIMIT));
        super.addFocusListener(this);
        this.addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent arg0) {

    }

    @Override
    public void keyReleased(KeyEvent arg0) {

    }

    @Override
    public void keyTyped(KeyEvent event) {
        char c = event.getKeyChar();

        if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)) {
            event.consume();
        }
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(this.getText().isEmpty()) {
        super.setText("");
        showingHint = false;
        }
    }
    @Override
    public void focusLost(FocusEvent e) {
        if(this.getText().isEmpty()) {
          super.setText(hint);
          showingHint = true;
        }
    }

    @Override
    public String getText() {
        return showingHint ? "" : super.getText();
    }
}

CustomJTextFieldCharLimit.java

public class CustomJTextFieldCharLimit extends PlainDocument{
    private int limit;

    public CustomJTextFieldCharLimit(int limit) {
        this.limit = limit;
    }

    public void insertString(int offset, String string, AttributeSet set) throws BadLocationException {
        if (string == null) {
            return ;
        }else if ((getLength() + string.length()) <= limit) {
            super.insertString(offset, string, set);
        }
    }
}

Solution

  • Okay, I'll check DocumentFilter in few min

    You haven't changed your code? The DocumentFilter is the preferred approach because it is reusable. You can add it to any Document so it will work for a JTextField, JTextArea, JTextPane.

    Both the requirements are working. But the problem is that if I set the limit to 6, then it sets the input length to 6. I need to set an additional limit.

    You need to use a different approach. For example you can use the Text Prompt class. The prompt is independent of the actual text so the lengths can be different.