Home > front end >  Is it possible to limit in a JTextField the area where characters can be inserted?
Is it possible to limit in a JTextField the area where characters can be inserted?

Time:10-22

I've a JTextField with a JButton positioned inside of it on the east side. At the moment, when characters inserted reach the button the part of the text overlapping is inserted below of it.

Here a snippet to reproduce the problem

class TextFieldWithIconLauncher {

    public static void main(String[] args) {
        JTextField modelFileTField = new JTextField();
        modelFileTField.setLayout(new BorderLayout());
        JButton button = new JButton("click");
        button.addActionListener(listener -> System.err.println("clicked!"));
        modelFileTField.add(button, BorderLayout.EAST);

        JFrame frame = new JFrame();
        frame.setSize(200, 100);
        frame.add(modelFileTField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(200, 100));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

These, instead, are screenshots of the real situation

Short text

Long text

I would like to avoid text overlapping with button without limiting the number of characters user can insert.

PS: If I add the JTextField and the JButton in a JPanel it works like a charm but I have some limitations and this approach at the moment isn't feasible unfortunately

CodePudding user response:

I resolved using FlatLaf Look and Feel (https://www.formdev.com/flatlaf/). In this way setting a specific property on the JTextField text and icon aren't overlapping anymore. Specifically I did:

class TextFieldWithIconLauncher {

    public static void main(String[] args) {
        JTextField textField = new JTextField();
        textField.setLayout(new BorderLayout());
        JButton button = new JButton("click");
        button.addActionListener(listener -> System.err.println("clicked!"));
        textField.add(button, BorderLayout.EAST);

        //Property to set
        textField.putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, button);

        JFrame frame = new JFrame();
        frame.setSize(200, 100);
        frame.add(modelFileTField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(200, 100));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
  • Related