change the size of JTextField on KeyPress

前端 未结 4 1075
臣服心动
臣服心动 2021-01-28 07:12

I have to extend the size of JTextField on KeyPressed event as user enter the text in textfield.please give me some idea how to achieve this?

thanks in advance

4条回答
  •  深忆病人
    2021-01-28 07:46

    Depends if you are using a LayoutManager or not. If not, attach a KeyListener to the JTextField and on keyRelease you need to calculate the length of the String (in pixels) and determine if the field needs to be updated

    addDocumentListener(new DocumentListener() {
    
        public void changedUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void insertUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void removeUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void updateField() {
    
            FontMetrics fm = getFontMetrics(getFont());
            String text = getText();
    
            int length = fm.stringWidth(text);
    
            Dimension size = getPreferredSize();
            Insets insets = getInsets();
            if (length < min) {
    
                size.width = min;
    
            } else {
    
                size.width = length + (insets.left + insets.right);
    
            }
    
            setSize(size);
            invalidate();
            repaint();
    
        }
    
    });
    

    Possibly a more sensible solution might be:

    addDocumentListener(new DocumentListener() {
    
        public void changedUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void insertUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void removeUpdate(DocumentEvent e) {
            updateField();
        }
    
        public void updateField() {
    
            setColumns(getText().length());
    
        }
    
    });
    

    I would also pay attention to what kleopatra & mKorbel have to say. While KeyListener might seem like a good idea, there are just to many situation's where it won't be notified - setText is the major one.

提交回复
热议问题