一切都在标题中。
在我的应用程序中,根据用户的选择,我填充一个组合框,其中列表有时可能很小(1个元素)有时很大(150个元素)。
我想要的是不是在启动时将固定高度设置为给定值,而是将maximumRowCount设置为我的JFrame的高度或我的屏幕高度,我不知道如何确定数字与我的应用程序高度或屏幕高度匹配的行数。这应该是动态的(在运行时),因此当我更改组合框字体大小时,maximumRowCount也会自行调整。
任何人都可以帮助我吗?
答案 0 :(得分:3)
以下是动态设置rowCount的代码段
基本步骤
代码(显然不是生产质量,只是为了给你一些玩法: - )
final JComboBox box = new JComboBox(new Object[] {1, 2, 3, 4, 5, 6, 6, 34,3,3});
PopupMenuListener l = new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
int pref = getRowHeight(box);
int available = getAvailableScreenHeightBelow(box);
int count = available / pref;
box.setMaximumRowCount(count);
}
private int getRowHeight(final JComboBox box) {
// note: here we assume the rendering comp's pref is the same for all rows
ComboPopup popup = (ComboPopup) box.getAccessibleContext().getAccessibleChild(0);
ListCellRenderer renderer = box.getRenderer();
Component comp = renderer.getListCellRendererComponent(popup.getList(), 1, 0, false, false);
int pref = comp.getPreferredSize().height;
return pref;
}
private int getAvailableScreenHeightBelow(final JComboBox box) {
// note: this is crude - f.i. doesn't take taskbar into account
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Point location = box.getLocationOnScreen();
location.y += box.getHeight();
int available = screen.height - location.y;
return available;
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
};
box.addPopupMenuListener(l);