如何让组合框的列表更宽广? [英] How can I make combobox's list wider?
本文介绍了如何让组合框的列表更宽广?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import javax.swing.*;
public class test
{
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(120,80);
JComboBox cb = new JComboBox();
cb.addItem("A very long combo-box item that doesn't fit no. 1");
cb.addItem("A very long combo-box item that doesn't fit no. 2");
frame.add(cb);
frame.validate();
frame.setVisible(true);
}
}
如何让组合框项目出现在所有文本都可见的方式?
现在我有这样的东西:
我不想在折叠时更改组合框的大小。
我只想增加展开部分的宽度。
How can I make combo-box items to appear in the way that all their text is visible?
Now I have something like this:
I don't want to change size of combo-box while collapsed.
I just want to increase width of the expanded part.
推荐答案
我认为此可能会有所帮助。
I think this may help.
来自链接的代码
public class WiderDropDownCombo extends JComboBox {
private String type;
private boolean layingOut = false;
private int widestLengh = 0;
private boolean wide = false;
public WiderDropDownCombo(Object[] objs) {
super(objs);
}
public boolean isWide() {
return wide;
}
// Setting the JComboBox wide
public void setWide(boolean wide) {
this.wide = wide;
widestLengh = getWidestItemWidth();
}
public Dimension getSize() {
Dimension dim = super.getSize();
if (!layingOut && isWide())
dim.width = Math.max(widestLengh, dim.width);
return dim;
}
public int getWidestItemWidth() {
int numOfItems = this.getItemCount();
Font font = this.getFont();
FontMetrics metrics = this.getFontMetrics(font);
int widest = 0;
for (int i = 0; i < numOfItems; i++) {
Object item = this.getItemAt(i);
int lineWidth = metrics.stringWidth(item.toString());
widest = Math.max(widest, lineWidth);
}
return widest + 5;
}
public void doLayout() {
try {
layingOut = true;
super.doLayout();
} finally {
layingOut = false;
}
}
public String getType() {
return type;
}
public void setType(String t) {
type = t;
}
public static void main(String[] args) {
String title = "Combo Test";
JFrame frame = new JFrame(title);
String[] items = {
"I need lot of width to be visible , oh am I visible now",
"I need lot of width to be visible , oh am I visible now" };
WiderDropDownCombo simpleCombo = new WiderDropDownCombo(items);
simpleCombo.setPreferredSize(new Dimension(180, 20));
simpleCombo.setWide(true);
JLabel label = new JLabel("Wider Drop Down Demo");
frame.getContentPane().add(simpleCombo, BorderLayout.NORTH);
frame.getContentPane().add(label, BorderLayout.SOUTH);
int width = 200;
int height = 150;
frame.setSize(width, height);
frame.setVisible(true);
}
}
这篇关于如何让组合框的列表更宽广?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文