Solve the problem of insufficient control width and incomplete display of drop-down content Modify the complete code
of com.datasweep.compatibility.ui.ComboBox.DefaultComboBox under the com.datasweep.compatibility.ui package
class DefaultComboBox extends JComboBox {
public DefaultComboBox(ComboBoxModel var2) {
super(var2);
}
/**
* Small hack to get pop up menu size bigger enough to show items even though
* the combo box size could be smaller
* */
private boolean layingOut = false;
@Override
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
@Override
public Dimension getSize(){
Dimension dim = super.getSize();
if ( !layingOut ) {
dim.width = Math.max(dim.width, computeMaxWith());
}
return dim;
}
public Integer computeMaxWith(){
Font font = this.getFont();
int maxWith = 0;
for (int i = 0; i < this.getModel().getSize(); i++) {
Object elementAt = this.getModel().getElementAt(i);
Integer width = getWidth(elementAt.toString(), font);
maxWith = Math.max(maxWith,width);
}
return maxWith+5;
}
public Integer getWidth(String text,Font font){
FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
int width = SwingUtilities.computeStringWidth(fm, text);
return width;
}
}