How can I change the width of a JComboBox dropdown list?

后端 未结 6 2135
自闭症患者
自闭症患者 2020-11-30 04:19

I have an editable JComboBox which contains a list of single letter values. Because of that the combobox is very small.

Every letter has a special mean

6条回答
  •  既然无缘
    2020-11-30 04:22

    I believe the only way to do this with the public API is to write a custom UI (there are two bugs dealing with this).

    If you just want something quick-and-dirty, I found this way to use implementation details to do it (here):

    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        JComboBox box = (JComboBox) e.getSource();
        Object comp = box.getUI().getAccessibleChild(box, 0);
        if (!(comp instanceof JPopupMenu)) return;
        JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0);
        Dimension size = new Dimension();
        size.width = box.getPreferredSize().width;
        size.height = scrollPane.getPreferredSize().height;
        scrollPane.setPreferredSize(size);
        //  following line for Tiger
        // scrollPane.setMaximumSize(size);
    }
    

    Put this in a PopupMenuListener and it might work for you.

    Or you could use the code from the first linked bug:

    class StyledComboBoxUI extends BasicComboBoxUI {
      protected ComboPopup createPopup() {
        BasicComboPopup popup = new BasicComboPopup(comboBox) {
          @Override
          protected Rectangle computePopupBounds(int px,int py,int pw,int ph) {
            return super.computePopupBounds(
                px,py,Math.max(comboBox.getPreferredSize().width,pw),ph
            );
          }
        };
        popup.getAccessibleContext().setAccessibleParent(comboBox);
        return popup;
      }
    }
    
    class StyledComboBox extends JComboBox {
      public StyledComboBox() {
        setUI(new StyledComboBoxUI());
      }
    }
    

提交回复
热议问题