How to have JComboBox drop down list which is wider than the JComboBox itself

情到浓时终转凉″ 提交于 2019-12-09 07:04:59

问题


By referring to the answer at Multi Columns Combo Box for Swing, I manage to implement a 3 multi columns JComboBox as follow.

However, this is not perfect. My intention is to have something without the horizontal scroll bar, as follow.

My question is, how can I have a JComboBox drop down list, which is wider than the JComboBox itself? I just want to get rid of the horizontal scroll bar. Yet, able to fit in 3 columns into a single list.

The source code are ResultSetCellRenderer and AjaxAutoCompleteJComboBox


回答1:


I got my problem resolved through the following forum Oracle Java Swing Forum

For future reference, I include the complete workable source code, for anyone who are interested.

AjaxAutoCompleteJComboBox.java




回答2:


I had the same problem, so I created the following method

 /**
     * 
     * @param box is the ComboBox that is about to show its own popup menu
     * @param metrics is used to calculate the width of your combo box's items
     */
    public static void adjustPopupWidth(JComboBox box,FontMetrics metrics) {
        if (box.getItemCount() == 0) {
            return;

        }
        Object comp = box.getUI().getAccessibleChild(box, 0);
        if (!(comp instanceof JPopupMenu)) {
            return;
        }


        //Find which option is the most wide, to set this width as pop up menu's preferred!
        int maxWidth=0;
        for(int i=0;i<box.getItemCount();i++){
            if(box.getItemAt(i)==null)
                continue;
            int currentWidth=metrics.stringWidth(box.getItemAt(i).toString());
            if(maxWidth<currentWidth)
                maxWidth=currentWidth;
        }
        JPopupMenu popup = (JPopupMenu) comp;
        JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
        Dimension size = scrollPane.getPreferredSize();
        // +20, as the vertical scroll bar occupy space too.
        size.width = maxWidth+20;
        scrollPane.setPreferredSize(size);
        scrollPane.setMaximumSize(size);
    }


来源:https://stackoverflow.com/questions/3969757/how-to-have-jcombobox-drop-down-list-which-is-wider-than-the-jcombobox-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!