gpt4 book ai didi

java - 无法从 DocumentListener 方法内部更改 JTextfield 的值

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:16:34 26 4
gpt4 key购买 nike

我收到“尝试在通知中更改”异常。1.我怎样才能改变它?2. 如何获取触发监听器之前 TextField 中的值?

编辑:

是这样的。在 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那做你想要的:

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

关于java - 无法从 DocumentListener 方法内部更改 JTextfield 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com