使 JComboBox 可编辑而不影响其宽度

发布于 2024-11-25 21:48:26 字数 438 浏览 3 评论 0原文

我的 JFrame 中有一个 JComboBox 对象,其行为完全符合预期。但是,我想让它可编辑,以便用户可以在必要时输入替代值。不幸的是,使用 setEditable(true) 启用编辑会导致其宽度显着增加。如何允许编辑 JComboBox,同时保持其宽度仅与最大可选项目所需的宽度相同?

JComboBox 位于带有 FlowLayoutJPanel 中,但是我认为这不相关,因为更改了 JPanel 的宽度 不影响 JComboBox 的宽度。

不可编辑的 jComboBox

I have a JComboBox object in my JFrame which behaves exactly as expected. However, I'd like to make it editable so that users can input alternative values if necessary. Unfortunately, using setEditable(true) to enable editing causes its width to increase significantly. How can I allow editing of the JComboBox while keeping its width only as wide as the largest selectable item requires?

The JComboBox is in a JPanel with a FlowLayout, however I don't think this is relevant because changing the width of the JPanel does not affect the width of the JComboBox.

uneditable jComboBox editable jComboBox

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

(り薆情海 2024-12-02 21:48:26

JTextField 有默认的首选大小。看起来,如果该大小大于首选呈现大小,则使用文本字段大小。您可以通过指定文本字段中显示的列数来更改首选大小。因此,您需要使用如下代码来操作编辑器:

JComboBox comboBox = new JComboBox( ... );
comboBox.setEditable( true );
ComboBoxEditor editor = comboBox.getEditor();
JTextField textField = (JTextField)editor.getEditorComponent();
textField.setColumns(3);

A JTextField has a default preferred size. It appears that if this size is greater than the preferred rendering size, then the text field size is used. You can change the preferred size by specifying the the number of columns to display in the text field. So you need to manipulate the editor with code something like:

JComboBox comboBox = new JComboBox( ... );
comboBox.setEditable( true );
ComboBoxEditor editor = comboBox.getEditor();
JTextField textField = (JTextField)editor.getEditorComponent();
textField.setColumns(3);
唱一曲作罢 2024-12-02 21:48:26

嗯...我无法在我的 Mac 上提示此行为,但您可以尝试创建/添加组合框,然后调用

Dimension size = box.getSize();
box.setEditable(true);
box.setSize(size); // or box.setMaximumSize(size);

Hmmm... I can't prompt this behavior on my Mac, but you might try creating/adding the combobox, then call

Dimension size = box.getSize();
box.setEditable(true);
box.setSize(size); // or box.setMaximumSize(size);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文