开发者

Make a JComboBox editable without affecting its width

开发者 https://www.devze.com 2023-03-22 13:06 出处:网络
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 setEditab

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 af开发者_如何学运维fect the width of the JComboBox.

Make a JComboBox editable without affecting its width

Make a JComboBox editable without affecting its width


JComboBox@setPrototypeDisplayValue("XXXXXXXXXXXXXX")


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);


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消