Java 如何让DocumentFilter与JComboBox一起工作

Java 如何让DocumentFilter与JComboBox一起工作,java,swing,jcombobox,keylistener,documentfilter,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 D

我以前在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);
}
public类InputField扩展JComboBox{
//寻求建议
私人建议查找器_finder;
//用于添加项的模型
私有默认ComboxModel\u模型;
公共输入字段(SuggestionFinder){
超级();
_model=新的DefaultComboxModel();
这个.setModel(_模型);
最大行数=5;
此.setEditable(true);
尺寸d=新尺寸(300,75);
这是设置最小尺寸(d);
此设置最大尺寸(d);
_查找器=查找器;
组件edComp=editor.getEditorComponent();
文档文档=((JTextComponent)edComp.getDocument();
if(普通文档的文档实例){
((纯文档)文档).setDocumentFilter(新文档过滤器(){
@凌驾
public void insertString(FilterBypass fb,int offset,
字符串字符串,AttributeSet attr)引发BadLocationException{
系统输出打印项次(“1”);
Document d=fb.getDocument();
给出建议(d.getText(0,d.getLength());
super.insertString(fb,offset,string,attr);
}
@凌驾
公共无效删除(FilterBypass fb、整数偏移量、整数长度)
抛出BadLocationException{
系统输出打印项次(“2”);
Document d=fb.getDocument();
给出建议(d.getText(0,d.getLength());
超级。删除(fb、偏移、长度);
}
@凌驾
公共无效替换(FilterBypass fb,整数偏移,整数长度,
字符串文本,属性集属性)引发BadLocationException{
系统输出打印项次(“3”);
Document d=fb.getDocument();
给出建议(d.getText(0,d.getLength());
super.replace(fb、偏移量、长度、文本、属性);
}
});
}
}
私人建议(字符串字){
System.out.println(word);
_model.removeAllElements();
if(字等于(“”){
this.hidePopup();
}
否则{
this.showPopup();
/*List suggs=\u finder.getSuggestions(word);

对于(int i=1;i某些信息告诉我,您不想这样做,而是真正想使用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;
   }
}
import java.io.IOException;
导入javax.swing.*;
导入javax.swing.text.*;
公共类文档过滤器{
公共静态void main(字符串[]args)引发IOException{
JPanel面板=新的JPanel();
InputField2 field2=新的InputField2();
panel.add(field2.getCombo());
JFrame=新JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
框架。添加(面板);
frame.pack();
frame.setVisible(true);
}
}
类输入字段2{
字符串[]foo={“1”、“2”、“3”};
私有jcombox组合=新jcombox(foo);
公共输入字段2(){
combo.setEditable(真);
Object editorComponent=combo.getEditor().getEditorComponent();
文档文档=((JTextComponent)编辑器组件).getDocument();
if(普通文档的文档实例){
((纯文档)文档).setDocumentFilter(新文档过滤器(){
@凌驾
public void insertString(FilterBypass fb,int offset,
字符串字符串,AttributeSet attr)引发BadLocationException{
Document doc=fb.getDocument();
StringBuilder sb=新的StringBuilder();
sb.append(doc.getText(0,doc.getLength());
System.out.println(“原始字符串:+sb.toString());
插入(偏移量、字符串);
System.out.println(“新字符串:+sb.toString());
super.insertString(fb,offset,string,attr);
}
@凌驾
公共无效删除(FilterBypass fb、整数偏移量、整数长度)
抛出BadLocationException{
Document doc=fb.getDocument();
StringBuilder sb=新的StringBuilder();
sb.append(doc.getText(0,doc.getLength());
System.out.println(“原始字符串:+sb.toString());
sb.删除(偏移量,偏移量+长度);
System.out.println(“新字符串:+sb.toString());
超级。删除(fb、偏移、长度);
}
@凌驾
公共无效替换(FilterBypass fb,整数偏移,整数长度,
字符串文本,属性集属性)引发BadLocationException{
Document doc=fb.getDocument();
StringBuilder sb=新的StringBuilder();
sb.append(doc.getText(0,doc.getLength());
System.out.println(“原始字符串:+sb.toString());
替换(偏移量,偏移量+长度,文本);
System.out.println(“新字符串:+sb.toString());
super.replace(fb、偏移量、长度、文本、属性);
}
});
}
}
公共JComponent getCombo(){
返回组合;
}
}

编辑正如我昨天在你的上一篇文章中提到的。

谢谢,我编辑了它,现在它可以正确地捕捉按键。但是,正如我编辑上面的问题来解释的那样,一旦我键入第二个字母,我就会得到一个奇怪的无限循环。错误消息是,它发生在我说的那行“this.showPopup()",你知道为什么会这样吗?事实上,我觉得这是别人给我的代码中的一个错误,谢谢你的帮助!如果我有任何后续问题,我会在这里再次回答。没关系,这肯定是一个问题。出于某种原因,第一个字母键入,然后下一个字母导致程序崩溃。Commenting out'this.showPopup()'行也没有帮助。