How to get a JComboBox dropdown that is wider than JComboBox itself

Turning to the answer to the Column field for multiple columns for Swing , I managed to implement 3 multichannel JComboBox columns, as shown below.

alt text

However, this is not ideal. My intention is to have something without a horizontal scrollbar, as it should. alt text

My question is: how can I release a JComboBox dropdown that is wider than JComboBox itself? I just want to get rid of the horizontal scrollbar. However, it can fit in 3 columns in one list.

Source Code ResultSetCellRenderer and AjaxAutoCompleteJComboBox

+5
2

,

 /**
     * 
     * @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 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 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);
    }
+1

All Articles