简体   繁体   English

选择文件时如何扩展/收缩JTextField

[英]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? 我该如何调整文本字段的大小以适合文件路径?

Packing the frame doesn't do anything. 包装框架没有任何作用。

Using frame.pack() will work. 使用frame.pack()将起作用。 The pack() causes the layout managers to be invoked. pack()导致布局管理器被调用。

encryptorFrame is a JFrame, which contains several sub-panels, cryptoorFrame是一个JFrame,其中包含几个子面板,

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. 然后,文本字段将使用10来提供首选大小,即使文本更改,该大小也不会更改。

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. 然后,您可以使用panel.revalidate()来调整面板中文本字段的大小,或者使用frame.pack()来调整整个框架的大小。

Or, since you are getting the file name from the file chooser, maybe you could just use a JLabel to display the name. 或者,由于您是从文件选择器获取文件名的,因此,您可以仅使用JLabel来显示名称。 A label will always calculated its preferred size based on the text. 标签将始终根据文本计算其首选大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM