2013-04-28 80 views
0

我有一個SWT文本小部件。我在窗口小部件裏面有文本,比如說「B for Bat」,我選擇了它的一部分(通過鼠標和鍵盤),即「蝙蝠」並通過按鈕觸發事件,其中我的代碼用「球」 。所以我最終的輸出是「B for Ball」。如何用新文本替換僅SWT中的選定文本

我該如何做到這一點。請幫我

回答

2

這將解決你的問題:

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(),它會返回一個Pointx座標選擇的開始和y座標的結束選擇。

您可能想要爲空選擇添加檢查。


BTW:請隨時張貼的內容你已經嘗試自己...

+0

感謝的快速反應。 getSelection()至關重要 – kk331317 2013-04-28 18:14:36

+0

@ kk331317不客氣。 – Baz 2013-04-28 18:16:32