JComboBox设置为可编辑的,如何限制只能输入数字?如何获取输入的内容? 

解决方案 »

  1.   

    new JComboBox().getEditor().getEditorComponent().addKeyListener(new KeyAdapter(){ 
    public void keyTyped(KeyEvent e){ 
    System.out.println(e); 
    } 当然要是想限定一下数字 可以做一个判断  我觉得
      

  2.   

    自己实现一个 ComboBoxEditor
      

  3.   

    isEditable()可编辑,getSelectedItem获取当前
      

  4.   

    谢谢各位的回复,你们的回复太简单了,解决不了问题,以下是我解决问题的代码:String[] fontSize = {"8","10","12","14","16","18","24","36","48","64","72"};
    jComboBox1 = new JComboBox(fontSize);
    jComboBox1.setEditable(true);
    jComboBox1.setMaximumRowCount(15);
    jComboBox1.setEditor(new Editor());
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
    Object obj = jComboBox1.getSelectedItem();
    String str = obj.toString();
    try{
          int size = Integer.parseInt(str);
          for(JhkMathBase base:page.selectedObjs){
     base.setFontSize(size);
          }
          page.jhkDrawPanel.repaint();
    }catch (NumberFormatException exc) {

    }
    }
    });自己实现的一个 ComboBoxEditor
    private class Editor implements ComboBoxEditor{ final protected JTextField editor;
    private EventListenerList listenerList = new EventListenerList();

    public Editor(){
    editor = new JTextField();
    editor.setDocument(new NumericDocument3());
    }

    @Override
    public void addActionListener(ActionListener l) {
    listenerList.add(ActionListener.class, l);
    } @Override
    public Component getEditorComponent() {
    return editor;
    } @Override
    public Object getItem() {
    return editor.getText();
    } @Override
    public void removeActionListener(ActionListener l) {
    listenerList.remove(ActionListener.class, l);
    } @Override
    public void selectAll() {
    } @Override
    public void setItem(Object newValue) {
    if (newValue instanceof String) {
    String sz = (String) newValue;
    editor.setText(sz);
    } else {
    editor.setText("");
    }
    }
    }
    限制只可以输入3位数字
    private class NumericDocument3 extends PlainDocument {
    private static final long serialVersionUID = 1L;

    public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException {
    if (str == null) {
    return;
    }
    if ((getLength() + str.length()) <= 3) {
    int length = 0;
    char[] upper = str.toCharArray();
    for (int i = 0; i < upper.length; i++) {
    if(offs+i==0 && upper[i]=='0'){ }else if (upper[i] >= '0' && upper[i] <= '9') {
    upper[length++] = upper[i];
    }
    }
    super.insertString(offs, new String(upper, 0, length), a);
    }
    }
    }
      

  5.   

    不用这么麻烦, 可以这样:ComboBoxEditor editor = jComboBox1.getEditor();
    JTextField textField = (JTextField)editor.getEditorComponent();
    textField.setDocument(NumericDocument3);