Alter JComboBox popup size without disturbing Look and Feel?

后端 未结 2 1610
旧时难觅i
旧时难觅i 2021-01-26 19:23

I\'m looking for a way to alter the width of a JComboBox\'s popup. Basically, the popup should be as wide as the widest combobox entry requires, not as wide as the combobox curr

2条回答
  •  孤独总比滥情好
    2021-01-26 19:35

    This hack seems to work with Java6/7. It basically overrides getSize() to detect if the method is called from within the popup UI. If it detects it is, it lies about the combobox's current size. The popup then determines its size according to faked size value.

    The detection code is brutal (it looks at the call stack) and built around the assumption that the calling class' name contains ComboPopup. It may fail to detect the condition on some UI implementations, in that case it will simply retain the default behavior.

    public class PopupHackComboBox extends JComboBox {
    
        // --------------------------------------------------------------
        // ---
        // --- Hack to get control of combobox popup size
        // ---
        // --------------------------------------------------------------
        /**
         * Gets the width the combo's popup should use.
         * 
         * Can be overwritten to return any width desired.
         */
        public int getPopupWidth() {
            final Dimension preferred = getPreferredSize();
            return Math.max(getWidth(), preferred.width);
        }
    
        @SuppressWarnings("deprecation")
        @Override
        public Dimension size() {
            return getSize((Dimension) null);
        }
    
        @Override
        public Dimension getSize() {
            return getSize((Dimension) null);
        }
    
        @Override
        public Dimension getSize(final Dimension dimension) {
            // If the method was called from the ComboPopup,
            // simply lie about the current size of the combo box.
            final int width = isCalledFromComboPopup() ? getPopupWidth() : getWidth();
            if (dimension == null) {
                return new Dimension(width, getHeight());
            }
            dimension.width = width;
            dimension.height = getHeight();
            return dimension;
        }
    
        /**
         * Hack method to determine if called from within the combo popup UI.
         */
        public boolean isCalledFromComboPopup() {
            try {
                final Throwable t = new Throwable();
                t.fillInStackTrace();
                StackTraceElement[] st = t.getStackTrace();
                // look only at top 5 elements of call stack
                int max = Math.min(st.length, 5);
                for (int i=0; i

提交回复
热议问题