Pregunta

Me estaba preguntando si hay algún tipo de magia que puede utilizar para obtener alrededor de un IllegalStateException y permitir un JTextField a "intentar mutar en la notificación", o en otras palabras, para establecer su propio texto si se activa su oyente.

Para su información, estoy tratando de programar una función de autocompletar que devuelve el partido más probable en una gama de 12 enumeraciones en respuesta a la entrada de un usuario en el JTextField.

Aquí está el ejemplo de código. Vas a tener que perdonar mi algoritmo torpe, que cruje a cabo los resultados de enumeración. He resaltado el código que produce la excepción con un comentario:

jtfElement1.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent e) {                    
                String s = jtfElement1.getText();
                int[] attributes = new int[13];
                // iterate through each enum
                for (BaseEnumAttributes b: BaseEnumAttributes.values()) {
                    // iterate through the length of the current text in jtfElement1
                    for (int i = 0; i < s.length(); i++) {
                        if (s.length() <= b.toString().length()) {                                
                            if (b.toString().charAt(i) == s.charAt(i)) {
                                // increase the number of "hits" noted for that enum
                                attributes[b.ordinal()] = attributes[b.ordinal()] + 1;
                            }                                
                        }
                    }                        
                }
                int priorC = 0;
                int rightC = 0;                    
                // iterate through the "array" of enums to find the highest score
                for (int j = 0; j < attributes.length; j++) {
                    if (attributes[j] > priorC) {
                        priorC = attributes[j];
                        rightC = j;
                    }
                }                    
                if (!s.equals("")) {
                    // assign to b the Enum corresponding to the "array" with highest score
                    BaseEnumAttributes b = BaseEnumAttributes.values()[rightC];
                    iController.updateInputElement1String(b.toString());                        
                    // THIS TRIGGERS EXCEPTION 
                    jtfElement1.setText(b.toString());
                }

            }
        });
¿Fue útil?

Solución

Usted es probablemente mejor usar un filtro de documento o un documento personalizado.

Lo que se espera que otros oyentes para ver si el documento no se mantiene igual durante el envío de eventos?

Otros consejos

Uso SwingUtilities.invokeLater () colocar todas las modificaciones allí

Tal vez se puede retrasar la setText () con un hilo de correr tras caretUpdate () ha terminado.

me encuentran en el mismo problema pero he encontrado una solución fácil:

bloquear el caretUpdate () por un valor lógico si (falso), mientras que u'r ajustar el texto a la JTextField de desbloqueo después. . algo como esto:

boolean caret = true;

private void listValueChanged (javax.swing.event.ListSelectionEvent evt) {         caret = false;         name.setText ((String) list.getSelectedValue ());         caret = true;     }

private void nameCaretUpdate(javax.swing.event.CaretEvent evt) {
   if(caret){
    model = new DefaultListModel();
    this.fillList(name.getText());
    list.setModel(model);
    }
}

Crea una alfombrilla de documentos y insertString anulación ()

filenameText = new JTextField(new FilenameDocument(), "", 0);

...

 /**
 * document which adds .xml extension if not specified
 *
 */
private class FilenameDocument extends PlainDocument {

    @Override
    public void insertString(int offset, String insertedText, AttributeSet set)
    throws BadLocationException {
        if (offset == 0) {
        insertedText = insertedText.trim( );
        }
        super.insertString(offset, insertedText, set);
        if (filenameText != null) {
            final int caretPos = filenameText.getCaretPosition();
            String text = filenameText.getText().trim();
            if (text.indexOf('.') == -1) {
                filenameText.setText(text + ".xml");
                filenameText.setCaretPosition(caretPos);
            }

        }
    }
}

Tenga en cuenta que llamar setText resultará en una llamada recursiva a insertString (), así que asegúrese de que usted tiene una condición de parada.

Me sorprende que nadie ha respondido a esto, pero WOULD'NT que ha sido mejor de la implementación de un editable JSpinner con un SpinnerListModel ?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top