gpt4 book ai didi

java - 将输入限制类更改为函数

转载 作者:行者123 更新时间:2023-11-30 03:32:06 26 4
gpt4 key购买 nike

我有一个基本类,它允许我限制在 JTextField (或与此相关的任何字段)中输入的字符数,但我想知道是否有一种方法可以将该类转换为函数,以便我可以将我的“实用程序”类中的函数以及我的其他辅助函数。如果我可以将限制作为函数的参数给出,那就太理想了。

目前它的名称是这样的:

textfield.setDocument(new InputLimit());

我希望能够这样调用它:

textfield.setDocument(Utilities.setInputLimit(10));

我的类(class)如下:

public class InputLimit extends PlainDocument {

private final int charLimit = 10;

InputLimit() {
super();
}

public void insertString(int offset, String str,
AttributeSet attr) throws BadLocationException {
if (str == null) {
return;
}

if ((getLength() + str.length()) <= charLimit) {
super.insertString(offset, str, attr);
}
}
}

最佳答案

您可以将 charLimit 作为构造函数参数传递为

textfield.setDocument(new InputLimit(10));

只需在您的类中添加以下构造函数

public class InputLimit extends PlainDocument {

private final int charLimit = 10;

// Keep this if you want a no-arg constructor too
InputLimit() { super(); }

// compiler will auto add the super() call for you
public InputLimit(int limit) { this.charLimit = limit; }

// ...
}

关于java - 将输入限制类更改为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28790552/

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