Java,Swing:如何设置JTextField的最大宽度? [英] Java, Swing: how do I set the maximum width of a JTextField?

查看:171
本文介绍了Java,Swing:如何设置JTextField的最大宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自定义文件选择组件。在我的UI中,首先用户点击一个按钮,弹出 JFileChooser ;当它关闭时,所选文件的绝对路径被写入 JTextField

I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a JFileChooser; when it is closed, the absolute path of the selected file is written to a JTextField.

问题是,绝对路径通常很长,导致文本字段放大,使其容器太宽。

The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.

我试过这个,但它没有做任何事情,文本字段仍然太宽:

I've tried this, but it didn't do anything, the text field is still too wide:

fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));

目前,当它为空时,已经是400px长,因为附加了GridBagConstraints

Currently, when it is empty, it is already 400px long, because of GridBagConstraints attached to it.

我希望它像HTML页面中的文本字段一样,具有固定的大小而不会放大当输入太长时。

I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.

那么,如何设置 JTextField的最大大小

推荐答案

它可能取决于文本字段所在的布局管理器。某些布局管理器会扩展,而有些布局管理器则不会。有些只在某些情况下扩展,有些则总是扩展。

It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always.

我假设你在做什么

filedNameTextField = new JTextField(80); // 80 == columns

如果是这样,对于大多数合理的布局,字段不应改变大小(至少,它不应该增长)。布局经理在放入 JScrollPane 时经常表现不佳。

If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow). Often layout managers behave badly when put into JScrollPanes.

根据我的经验,尝试通过<控制尺寸 setMaximumSize setPreferredWidth 等等充其量是不稳定的。 Swing自己决定使用布局管理器,而你几乎无能为力。

In my experience, trying to control the sizes via setMaximumSize and setPreferredWidth and so on are precarious at best. Swing decided on its own with the layout manager and there's little you can do about it.

所有这些,我没有遇到你遇到的问题,这导致我相信一些明智的使用布局管理器将解决问题。

All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem.

这篇关于Java,Swing:如何设置JTextField的最大宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆