62,597
社区成员




class MyComboBoxUI extends WindowsComboBoxUI {
protected ComboPopup createPopup() {
return new MyComboBoxPopup(comboBox);
}
}
class MyComboBoxPopup extends BasicComboPopup {
public MyComboBoxPopup(JComboBox combo) {
super(combo);
}
protected JScrollPane createScroller() {
JScrollPane sp = new JScrollPane( list,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
return sp;
}
public void show() {
setListSelection(comboBox.getSelectedIndex());
Insets insets = getInsets();
int popupPrefWid = list.getPreferredSize().width + insets.left + insets.right;
Dimension scrollSize = new Dimension(
comboBox.getWidth(), getPopupHeightForRowCount( comboBox.getMaximumRowCount()));
if (popupPrefWid > scrollSize.width) {
scrollSize.height += scroller.getHorizontalScrollBar().getPreferredSize().height;
}
scroller.setMaximumSize( scrollSize );
scroller.setPreferredSize( scrollSize );
scroller.setMinimumSize( scrollSize );
list.revalidate();
show( comboBox, 0, comboBox.getHeight());
}
private void setListSelection(int selectedIndex) {
if ( selectedIndex == -1 ) {
list.clearSelection();
}else{
list.setSelectedIndex(selectedIndex);
list.ensureIndexIsVisible(selectedIndex);
}
}
}
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
public class WideComboBox extends JComboBox{
/**
*
*/
private static final long serialVersionUID = 1L;
private ArrayList<String> arrvalue = new ArrayList<String>();
public WideComboBox() {
}
public WideComboBox(final Object items[], final String[] values){
super(items);
for(int i=0; i < values.length; i++){
this.arrvalue.add(values[i]);
}
}
public WideComboBox(Vector items) {
super(items);
}
public WideComboBox(ComboBoxModel aModel) {
super(aModel);
}
public void addItem(Object anObject,String value){
super.addItem(anObject);
this.arrvalue.add(value);
}
public String getValue(){
int x = this.getSelectedIndex();
return (String)arrvalue.get(x);
}
private boolean layingOut = false;
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
public Dimension getSize(){
Dimension dim = super.getSize();
if(!layingOut)
dim.width = Math.max(dim.width, getPreferredSize().width);
return dim;
}
}
package april.test0414;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestJcombox extends JFrame{
String str[]={"aa","bb","cc","dd","ee"};
public TestJcombox() {
JComboBox box=new JComboBox(str);
box.setPreferredSize(new Dimension(10,20));//设置下拉框的高和宽
box.setEditable(false);
this.add(new JPanel().add(box));
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new TestJcombox();
}
}