java jtextfield不可编辑_java - java-无法从DocumentListener方法内部更改JTextfield的值

我收到“尝试在通知中进行变异”异常。

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,它避免了任何递归调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值