如何让DocumentFilter与JComboBox一起使用

时间:2013-04-02 22:11:00

标签: java swing jcombobox keylistener documentfilter

我之前使用DocumentListener尝试了这个,但是在我听到某些内容之后,这也给我带来了编辑文档的问题。现在我正在尝试使用DocumentFilter,它似乎正在工作。

public class InputField extends JComboBox<String>{

//for finding suggestions
private SuggestionFinder _finder;
//the model to use for adding items
private DefaultComboBoxModel<String> _model;

public InputField(SuggestionFinder finder){
    super();
    _model = new DefaultComboBoxModel();
    this.setModel(_model);
    maximumRowCount = 5;
    this.setEditable(true);
    Dimension d = new Dimension(300, 75);
    this.setMinimumSize(d);
    this.setMaximumSize(d);
    _finder = finder;
    Component edComp = editor.getEditorComponent();
    Document document = ((JTextComponent)edComp).getDocument();
    if (document instanceof PlainDocument) {
     ((PlainDocument) document).setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset,
              String string, AttributeSet attr) throws BadLocationException {
            System.out.println("1");
            Document d = fb.getDocument();
            giveSuggestions(d.getText(0, d.getLength()));
            super.insertString(fb, offset, string, attr);
        }

        @Override
        public void remove(FilterBypass fb, int offset, int length)
              throws BadLocationException {
            System.out.println("2");
            Document d = fb.getDocument();
            giveSuggestions(d.getText(0, d.getLength()));
            super.remove(fb, offset, length);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length,
              String text, AttributeSet attrs) throws BadLocationException {
            System.out.println("3");
            Document d = fb.getDocument();
            giveSuggestions(d.getText(0, d.getLength()));
            super.replace(fb, offset, length, text, attrs);
        }
     });
  }
}

private void giveSuggestions(String word){
    System.out.println(word);
    _model.removeAllElements();
    if (word.equals("")){
        this.hidePopup();
    }
    else{
        this.showPopup();
        /*List<String> suggs = _finder.getSuggestions(word);
        for (int i = 1; i <= suggs.size(); i++){
            _model.addElement(suggs.get(i-1));
        }*/
        for (int i = 0; i < 5; i++){
            System.out.println("adding");
            _model.addElement("" + Math.floor(Math.random()*100));
        }
    }
    System.out.println("done");
}

public static void main(String[] args) throws IOException{
    //instantiate a finder, how I do this isn't really relevant to my issue
    InputField field = new InputField(finder);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(field);
    frame.pack();
    frame.setVisible(true);
}

1 个答案:

答案 0 :(得分:2)

有些东西告诉我你不想这样做,而是你真的想要使用DocumentFilter。例如:

import java.io.IOException;
import javax.swing.*;
import javax.swing.text.*;

public class DocFilterEg {
   public static void main(String[] args) throws IOException {
      JPanel panel = new JPanel();      
      InputField2 field2 = new InputField2();

      panel.add(field2.getCombo());

      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.pack();
      frame.setVisible(true);
   }
}

class InputField2 {
   String[] foo = {"1", "2", "3"};
   private JComboBox<String> combo = new JComboBox<String>(foo);

   public InputField2() {
      combo.setEditable(true);
      Object editorComponent = combo.getEditor().getEditorComponent();
      Document document = ((JTextComponent)editorComponent).getDocument();

      if (document instanceof PlainDocument) {
         ((PlainDocument) document).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                  String string, AttributeSet attr) throws BadLocationException {

               Document doc = fb.getDocument();
               StringBuilder sb = new StringBuilder();
               sb.append(doc.getText(0, doc.getLength()));
               System.out.println("Original String: " + sb.toString());
               sb.insert(offset, string);
               System.out.println("New String:      " + sb.toString());

               super.insertString(fb, offset, string, attr);
            }

            @Override
            public void remove(FilterBypass fb, int offset, int length)
                  throws BadLocationException {

               Document doc = fb.getDocument();
               StringBuilder sb = new StringBuilder();
               sb.append(doc.getText(0, doc.getLength()));
               System.out.println("Original String: " + sb.toString());
               sb.delete(offset, offset + length);
               System.out.println("New String:      " + sb.toString());

               super.remove(fb, offset, length);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                  String text, AttributeSet attrs) throws BadLocationException {

               Document doc = fb.getDocument();
               StringBuilder sb = new StringBuilder();
               sb.append(doc.getText(0, doc.getLength()));
               System.out.println("Original String: " + sb.toString());
               sb.replace(offset, offset + length, text);
               System.out.println("New String:      " + sb.toString());

               super.replace(fb, offset, length, text, attrs);
            }
         });
      }
   }

   public JComponent getCombo() {
      return combo;
   }
}

编辑正如我之前在您之前的帖子中提到的那样。