Не могу изменить значение поля JText из методов DocumentListener - PullRequest
3 голосов
/ 22 мая 2011

Я получаю исключение "Попытка изменить в уведомлении". 1. Как я могу это изменить? 2. Как я могу получить значение, которое было внутри TextField до запуска слушателя?

EDIT:

Это что-то вроде этого. На JTextfield у меня есть этот слушатель

basePriceTF.getDocument().addDocumentListener(new DocumentListener(){ 
     public void insertUpdate(DocumentEvent e){ 
        if (Integer.getValue(basePriceTF.getText())<0){
        basePriceTF.setText("0");
        }
     }

     public void removeUpdate(DocumentEvent e){/**my implemntation**/}

     public void changedUpdate(DocumentEvent e){/**my implemntation**/}
}

insertUpdate() will probably cause a loop.
So it doesnt let me change inside basePriceTF.

Ответы [ 3 ]

4 голосов
/ 23 мая 2011

Как уже было отмечено три раза, именно для этого и созданы DocumentFilter с.Вот SSCCE , который делает то, что вы хотите:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.AttributeSet;

public class TestDocumentFilter extends JFrame {
  JTextField basePriceTF;

public TestDocumentFilter() {
    super("TestDocumentFilter");
    basePriceTF = new JTextField();
    AbstractDocument basePriceDocument = (AbstractDocument) basePriceTF.getDocument();
    basePriceDocument.setDocumentFilter(new PositiveIntegerFilter());
    getContentPane().add(basePriceTF);
}

/**
 * Resets the document to "0" for input values that do not constitut a non-negative integer.
 */
private static class PositiveIntegerFilter extends DocumentFilter {

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String inputTextValue,
            AttributeSet attrs) throws BadLocationException {
        Document oldDoc = fb.getDocument();
        String textValue = oldDoc.getText(0, oldDoc.getLength()) + inputTextValue;
        Integer basePrice = 0;
        try {
            basePrice = Integer.parseInt(textValue);
        } catch (NumberFormatException e) { 
            basePrice = 0;
        }
        if (basePrice < 0) 
            basePrice = 0;
        fb.replace(0, oldDoc.getLength(), basePrice.toString(), attrs);
    }
}

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new TestDocumentFilter();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        }
    });
}
}

Вы не можете ввести "-1";поле сбрасывается в «0», когда набирается «-».Обратите внимание на FilterBypass, который избегает любых рекурсивных вызовов.

3 голосов
/ 22 мая 2011

Согласно учебному документу DocumentListener и API, DocumentListeners не должны изменять содержимое документа, поэтому краткий ответ таков: не делайте этого.

Рассмотрите возможность использования чего-то еще, например DocumentFilter или какого-либо другого проверяющего метода.

1 голос
/ 22 мая 2011

Это, вероятно, не очень хорошая практика, но она должна работать, и она не требует сложных и дорогих вещей.

final Document doc = basePriceTF.getDocument();
basePriceTF.getDocument().addDocumentListener(new DocumentListener(){
     public void insertUpdate(DocumentEvent e){
        if (Integer.getValue(basePriceTF.getText())<0){
            new Thread(new Runnable() {
                public void run() {
                    doc.removeDocumentListener(this);
                    basePriceTF.setText("0");        
                    doc.addDocumentListener(this);
                }
            }).start();
        }     
     }
     .......

Вы также можете использовать SwingUtilities.invokeLater (), если боитесь выполнить код в неправильный момент. Это также должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...