有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调整jcombobox下拉菜单的宽度

有没有办法调整JCombobox的下拉窗口大小

假设我有:

comArmor.setBounds(81, 102, 194, 26);

但是,当用户选择该框并弹出下拉列表时,我希望下拉窗口能够展开,以便完整地显示一长行文本(例如,大小x为300)

这可能吗


共 (2) 个答案

  1. # 1 楼答案

    不确定是否已经有此功能的内置功能,但您可以始终使用一个ActionListener侦听选择更改,然后在更改时以编程方式将JComboBox的宽度设置为所选内容的长度(^{}

    box.addActionListener (new ActionListener () {
        public void actionPerformed(ActionEvent e) {
            String item = comboBox.getSelectedItem().toString();
            comboBox.setBounds(81, 102, item.length * CONSTANT, 26);
        }
    });
    

    对我来说,这似乎有点老套,你可能不得不玩弄这个想法才能让它发挥作用

    我希望这对你有帮助

    更新:

    JComboBox似乎有一个^{}方法,用于根据参数的长度计算组件的首选宽度

    Sets the prototype display value used to calculate the size of the display for the UI portion.

    我可能会考虑使用这个。

  2. # 2 楼答案

    enter image description here

    小黑客得到弹出菜单的大小足够大,以显示项目,即使组合框的大小可以更小

    资料来源:http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough

        import java.awt.Dimension;
        import java.util.Vector;
    
        import javax.swing.ComboBoxModel;
        import javax.swing.JComboBox;
    
        public class ComboBoxFullMenu<E> extends JComboBox<E> {
    
            public ComboBoxFullMenu(E[] items) {
                super(items);
                addActionListener(this);
            }
    
            public ComboBoxFullMenu(Vector<E> items) {
                super(items);
                addActionListener(this);
            }
    
            public ComboBoxFullMenu(ComboBoxModel<E> aModel) {
                super(aModel);
                addActionListener(this);
            }
    
            /**
             * Small hack to get pop up menu size bigger enough to show items even though
             * the combo box size could be smaller
             * */
            private boolean layingOut = false; 
    
            @Override
            public void doLayout(){ 
                try{ 
                    layingOut = true; 
                    super.doLayout(); 
                }finally{ 
                    layingOut = false; 
                } 
            } 
    
            @Override
            public Dimension getSize(){ 
                Dimension dim = super.getSize(); 
                if ( !layingOut ) {
                    dim.width = Math.max(dim.width, getPreferredSize().width);
                }
                return dim; 
            }
        }