2010-10-19 50 views
5

宽。通过在Multi Columns Combo Box for Swing参考答案,我设法实现3个多列的JComboBox如下。如何有JComboBox的下拉列表,它比的JComboBox本身

alt text

然而,这是不完美的。我的意图是有没有水平滚动条,如下。 alt text

我的问题是,我怎么能有一个JComboBox下拉列表,它比JComboBox本身更宽?我只想摆脱水平滚动条。然而,能够将3列合并到一个列表中。

的源代码是ResultSetCellRendererAjaxAutoCompleteJComboBox

回答

1

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

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