Henry Copper
Henry Copper

Reputation: 1

Textfield Sometimes Highlighted When getFocusInWindow() Called

I have a vertical BoxLayout with a few JTextfields. Whenever one of the fields is edited, I would like the field to come to the top: I do this by removing the field and re-adding it to the top. However, when this is done, the textfield loses focus. Therefore, whenever a textfield is edited, I call requestFocusInWindow() on it. However, if the user's caret was previously (before the removal and re-adding) on the end of the line, and only in this instance, the whole textfield will be highlighted. If the user's caret was anywhere before the end of the line, this does not happen. This is an unwanted behaviour - the cursor should just stay at the end if it was there previously, and no highlighting should take place. An example is provided below. Try editing any of the textfields.

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Main {
    public static void main(String[] args) {
        var frame = new JFrame();
        var panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        frame.add(panel);

        var text1 = new JTextField();
        var text2 = new JTextField();
        var text3 = new JTextField();
        moveUpOnEdit(panel, text1, text2, text3);

        frame.pack();
        frame.setVisible(true);
    }

    public static void moveUpOnEdit(JPanel container, JTextField... textFields) {
        for (JTextField textField : textFields) {
            container.add(textField);
            textField.getDocument().addDocumentListener(new DocumentListener() {
                public void insertUpdate(DocumentEvent e) {changedUpdate(e);}

                public void removeUpdate(DocumentEvent e) {changedUpdate(e);}

                public void changedUpdate(DocumentEvent e) {
                    container.remove(textField);
                    container.add(textField, 0);
                    container.revalidate();
                    textField.requestFocusInWindow();
                }
            });
        }
    }

}

I have tried:

Nothing has thus far worked.

Upvotes: 0

Views: 45

Answers (0)

Related Questions