我收到“尝试在通知中进行变异”异常。
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.
正如迄今为止三度指出的那样,
这正是DocumentFilter
是为。
这里有一个SSCCE http://sscce.org/这就是你想要的:
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
这避免了任何递归调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)