問題描述
在 SWT 瀏覽器小部件中獲取選定文本 (Getting a Selected Text In SWT Browser Widgets)
I am implementing SWT Browser in my Project for displaying a WebPage. After displaying a web page into this browser, if a user selects particular text, how can I get the selected text? please help me with suitable example
參考解法
方法 1:
Maybe this link will help you out.
This link posits the idea of using a StatusTextListener to intercept text selections. Below is a snippet of the StatusTextListener implementation.
// Status Text Listener Interface.
public void changed (StatusTextEvent evt) {
String text = evt.text;
if ((text != null) && (text.length() > 0)) {
if ((! text.equalsIgnoreCase ("Done")) && (! text.equals (lastStatusText))) {
System.err.println (evt.text);
lastStatusText = text;
}
}
} // End of changed().
方法 2:
This seems to work well for me. Give it a try.
static String SCRIPT01 = "var html = \"\";"+
"if (typeof window.getSelection != \"undefined\") {"+
"var sel = window.getSelection();"+
"if (sel.rangeCount) {"+
"var container = document.createElement(\"div\");"+
"for (var i = 0, len = sel.rangeCount; i < len; ++i) {"+
"container.appendChild(sel.getRangeAt(i).cloneContents());"+
"}"+
"html = container.innerHTML;"+
"}"+
"} else if (typeof document.selection != \"undefined\") {"+
"if (document.selection.type == \"Text\") {"+
"html = document.selection.createRange().htmlText;"+
"}" +
"}" +
"return html";
browser.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent arg0) {
String selection = (String) browser.evaluate(SCRIPT01);
}
@Override
public void mouseDown(MouseEvent arg0) {
}
@Override
public void mouseDoubleClick(MouseEvent arg0) {
String selection = (String) browser.evaluate(SCRIPT01);
}
});
(by Abhit、Adam Green、Adam Green)