JComboBox具有较大的下拉宽度

问题描述 投票:1回答:2

问题:我有一个组合框,需要将其放入Swing应用程序的固定空间中。但是,其内容可能很长。我希望包装盒本身的尺寸固定,可以截断内容。但是,当单击向下箭头时,我希望它的行为类似于HTML select,并显示一个足够长的框以适合最长的下拉列表。 ListCellRenderer可能是进行此操作的一种方法。我不确定。

也可能是我需要某种javax.swing.plaf.basic.ComboPopup实现和我自己的ComboBoxUI。我已经研究了SwingUtilities代码,以了解DefaultListCellRenderer如何进行其计算。它使用JLabel,BasicLabelUI调用SwingUtilities.layoutCompoundLabel(最终在调用堆栈中)进行剪辑。我正在研究的Java 6代码中ComboPopup的唯一实现BasicComboPopup似乎委托给:JList.computeVisibleRect(组件c,矩形visibleRect)

以前有人这样做吗?有指针吗?

swing jcombobox
2个回答

1
投票

JComboBox由匿名者使用,宽度可变下拉列表。请注意,这仅是金属LAF。

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.metal.*;
import javax.swing.plaf.basic.*;

/**
 * @version 1.0 12/12/98
 * updated 2012-02-18 to include @Overrides and other Java needs
 */
class SteppedComboBoxUI extends MetalComboBoxUI {
  @SuppressWarnings("serial")
@Override
  protected ComboPopup createPopup() {
    BasicComboPopup popup = new BasicComboPopup( comboBox ) {

      @Override
    public void show() {
        Dimension popupSize = ((SteppedComboBox)comboBox).getPopupSize();
        popupSize.setSize( popupSize.width,
          getPopupHeightForRowCount( comboBox.getMaximumRowCount() ) );
        Rectangle popupBounds = computePopupBounds( 0,
          comboBox.getBounds().height, popupSize.width, popupSize.height);
        scroller.setMaximumSize( popupBounds.getSize() );
        scroller.setPreferredSize( popupBounds.getSize() );
        scroller.setMinimumSize( popupBounds.getSize() );
        list.invalidate();            
        int selectedIndex = comboBox.getSelectedIndex();
        if ( selectedIndex == -1 ) {
          list.clearSelection();
        } else {
          list.setSelectedIndex( selectedIndex );
        }            
        list.ensureIndexIsVisible( list.getSelectedIndex() );
        setLightWeightPopupEnabled( comboBox.isLightWeightPopupEnabled() );

        show( comboBox, popupBounds.x, popupBounds.y );
      }
    };
    popup.getAccessibleContext().setAccessibleParent(comboBox);
    return popup;
  }
}


@SuppressWarnings("serial")
public class SteppedComboBox extends JComboBox {
  protected int popupWidth;

  public SteppedComboBox(ComboBoxModel aModel) {
    super(aModel);
    setUI(new SteppedComboBoxUI());
    popupWidth = 0;
  }

  public SteppedComboBox(final Object[] items) {
    super(items);
    setUI(new SteppedComboBoxUI());
    popupWidth = 0;
  }

  @SuppressWarnings("unchecked")
public SteppedComboBox(Vector items) {
    super(items);
    setUI(new SteppedComboBoxUI());
    popupWidth = 0;
  }


  public void setPopupWidth(int width) {
    popupWidth = width;
  }

  public Dimension getPopupSize() {
    Dimension size = getSize();
    if (popupWidth < 1) popupWidth = size.width;
    return new Dimension(popupWidth, size.height);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.