简体   繁体   中英

VerifyListener not allowing CTRL + X action in SWT Text

When I add a VerifyListener to allow typing numbers only to a Text , Ctrl + x function is not working. The content of the text box is not cleared. Ctrl + c works fine.

What might be the reason for this?

@Override
public void verifyText(VerifyEvent e) {
    char inputChar = e.character;
    int keyCode = e.keyCode;
    e.doit = Character.isDigit(inputChar) || keyCode == SWT.BS || keyCode == SWT.DEL;
    }
}

You specifically need to allow the Text to be empty, ie in your Listener for SWT.Verify , check if it's empty and then check if it's a number. This will do the trick:

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

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

    text.addListener(SWT.Verify, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            Text source = (Text) event.widget;
            String oldString = source.getText();

            String newString =  oldString.substring(0, event.start) + event.text + oldString.substring(event.end);

            if(newString.length() == 0)
            {
                return;
            }
            else
            {
                try
                {
                    Double.parseDouble(newString); // Or Integer.parseInt(newString);
                }
                catch (NumberFormatException e)
                {
                    event.doit = false;
                }
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}
@Override
 public void verifyText(VerifyEvent e) {
      char inputChar = e.character;
      int keyCode = e.keyCode;
      String inputString = e.text;
      e.doit = Character.isDigit(inputChar) || keyCode == SWT.BS || keyCode==SWT.DEL||inputString=="";
}

I add a check on the text obtained from the Text widget if it is "", and it is working fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM