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

前端 未结 2 1759
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 02:19

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

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-10 03:01

    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

提交回复
热议问题