gpt4 book ai didi

java - SWT:获取即将从文本小部件中删除的字符数

转载 作者:行者123 更新时间:2023-12-01 12:04:11 26 4
gpt4 key购买 nike

我正在验证来自某些 SWT 文本小部件的输入。
假设用户使用鼠标或Ctrl. + A选择了他自己插入到小部件中的文本的某些部分。等等,然后按删除;如何获取即将删除的字符数?我正在使用 SWT 验证事件进行输入验证。文档说 event.text 将给出“将插入的新文本。[...]”并且能够修改将被删除的文本,但我无法找到一种方法来获取金额将被删除的文本。

谷歌也没有给我答案。有人知道如何实现这一目标吗?

由于实际代码相当冗长,我不得不删除不必要的部分才能将其发布到此处:

该代码的目的是获取 32 个十六进制数字并允许复制/粘贴。

int len = 0;
// input is a SWT Text widget with initial text set to ""
input.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e){
e.doit = false;
int addit = 0;
// do nothing when there are already 32 characters in the widget
if (len == 32){
return;
}
// allow Ctrl + v to paste
if(((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'v') && (len + e.text.length()) <= 32){
e.doit = true;
// here it works like a charm
addit = e.text.length();
}
// allow deleting characters: Problem: deleting multiple characters at a time
if (e.keyCode == SWT.BS || e.keyCode == SWT.DEL){
e.doit = true;
addit = ???; // this is the problem: how many characters are deleted, when the key is pressed
}
// isHex is a function that checks, weather e.character is a hexadecimal digit
if (isHex(e.character) || Character.isDigit(e.character) && len+1 <= 32){
e.doit = true;
addit = 1;
} else if (e.keyCode != SWT.BS && e.keyCode != SWT.BS && ((e.stateMask & SWT.CTRL) != SWT.CTRL) && e.keyCode != 'v') {
System.out.println(e.character + " is not valid");
return;
}
len += addit;
if (len == 32){
somemethod();
}
// print how many characters are there the moment the user types or deletes them
System.out.println((32 - len) + "chars");
}});
}

最佳答案

您可以简单地比较原始文本和验证事件后用户修改的长度。听SWT.Verify并比较长度:

public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell();
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());

final Text text = new Text(shell, SWT.BORDER);

text.addListener(SWT.Verify, new Listener()
{
@Override
public void handleEvent(Event e)
{
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

int difference = oldS.length() - newS.length();

if(difference > 0)
System.out.println("User deleted " + difference + " characters");
else if(difference < 0)
System.out.println("User added " + Math.abs(difference) + " characters");
}
});

shell.pack();
shell.open();

while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}

关于java - SWT:获取即将从文本小部件中删除的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765590/

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