代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

如何让jcombobox下拉列表比jcombobox本身更宽

  •  5
  • Cheok Yan Cheng  · 技术社区  · 15 年前

    通过参考 multi columns combo box for swing,i manage to implement a 3 multi columns jcombobox as follow.

    然而,这并不完美。我的目的是要有没有水平滚动条的东西,如下所示。

    我的问题是,我怎么能有一个JComboBox下拉列表,它比JComboBox本身还要宽?我只想去掉水平滚动条。但是,能够将3列内容放入一个列表中。

    源代码是 resultsetcellenderer and ajaxautoCompletejcombobox >p我设法实现了一个3列的JComboBox,如下所示。

    alt text

    然而,这并不完美。我的目的是要有没有水平滚动条的东西,如下所示。 alt text

    我的问题是,我怎么能有一个JComboBox下拉列表,它比JComboBox本身还要宽?我只想去掉水平滚动条。但是,能够将3列放入一个列表中。

    源代码是 ResultSetCellRenderer AjaxAutoCompleteJComboBox

    2 回复  |  直到 15 年前
        1
  •  4
  •   Cheok Yan Cheng    15 年前

    我通过下面的论坛解决了我的问题 Oracle Java Swing Forum

    为了将来的参考,我为任何感兴趣的人提供了完整的可操作的源代码。

    AjaxAutoCompleteJComboBox.java

        2
  •  1
  •   Gorbas    15 年前

    我有同样的问题,所以我创建了以下方法

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