Search code examples
javaswingjframejtextfield

How to expand/contract JTextField upon choosing file


I am trying to make it so that after choosing a file, the text field showing the file path is automatically contracted/expanded to fit the path.

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(encryptorFrame) == JFileChooser.APPROVE_OPTION) {
    chosenKeyFileTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
    encryptorFrame.pack();
}

Packing the frame doesn't do anything. How can I make it so that the text field is resized enough to fit the file path?


Solution

  • Packing the frame doesn't do anything.

    Using frame.pack() will work. The pack() causes the layout managers to be invoked.

    encryptorFrame is a JFrame, which contains several sub-panels,

    So it depends on the layout managers used and on the how you declare your text field.

    For example if you use:

    JTextField textField = new JTextField(10);
    

    Then the 10 will be used by the text field to provide a preferred size which will not change even as the text changes.

    However, if you use:

    JTextField textField = new JTextField();
    

    Then the preferred size will be based on the text in the text field.

    So you need to make sure that the panel you add the text field to is using a layout manager that will respect the preferred size of the text field.

    Then you can just use panel.revalidate() to resize the text field within the panel or frame.pack() to resize the entire frame.

    Or, since you are getting the file name from the file chooser, maybe you could just use a JLabel to display the name. A label will always calculated its preferred size based on the text.