【问题标题】:Get text of SWT Text component before modification获取SWT Text组件修改前的文本
【发布时间】:2015-12-28 14:27:58
【问题描述】:

我有一个带有 Modify 侦听器的 SWT Text 组件,当我在 Text 上写一些东西时,侦听器代码被执行,在侦听器内部我获取并打印新文本,例如,如果原始文本是"initial text",当我输入一些东西时,比如说"initial text2",监听器会打印"initial text2",这很好,但我还需要在修改文本之前的原始文本。

有没有办法做到这一点?我不想使用keyPressed 监听器,因为当用户使用鼠标粘贴文本时它不会处理。

到目前为止,我的代码如下所示:

Text myText = new Text(parent, SWT.NONE);
myText.setText("initial text");

myText.addModifyListener(new ModifyListener() {
    public void modifyText(ModifyEvent e) {
        //Get here the original text
        String content = myText.getText(); //This line return the modified string
    }
});

【问题讨论】:

    标签: java swt listener


    【解决方案1】:

    收听SWT.Verify 而不是SWT.Modify

    Text text = new Text(shell, SWT.BORDER);
    text.addListener(SWT.Verify, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            // Get the source widget
            Text source = (Text) e.widget;
    
            // Get the text
            final String oldS = source.getText();
            final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
    
            System.out.println(oldS + " -> " + newS);
        }
    });
    

    这将打印修改前后的文本。

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 2023-03-03
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多