我有一个 SWT 文本小部件。我在小部件内有文本,例如“B代表 bat ”,我选择(通过鼠标和键盘)其中的一部分,即“ bat ”,并通过按钮触发一个事件,其中我有我的代码替换为“球” 。所以我的最终输出将是“B for Ball”。
我该如何实现这一目标。请帮助我
最佳答案
这将解决您的问题:
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout(SWT.VERTICAL));
shell.setText("StackOverflow");
final Text text = new Text(shell, SWT.BORDER);
Button button = new Button(shell, SWT.PUSH);
button.setText("Replace");
button.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
String content = text.getText();
Point selection = text.getSelection();
/* Get the first non-selected part, add "Ball" and get the second non-selected part */
content = content.substring(0, selection.x) + "Ball" + content.substring(selection.y, content.length());
text.setText(content);
}
});
shell.pack();
shell.setSize(400,shell.getSize().y);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
关键部分是使用Text#getSelection()
,它将返回一个 Point
,其 x
坐标是选择的开始位置,y
坐标是选择的结束位置。
您可能想要添加对空选择的检查。
<小时/>顺便说一句:请始终发布您自己尝试过的内容...
关于java - 如何仅用新文本替换 SWT 中选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16265820/