在使用 Browser 控件的时候,右击 Browser 的显示区域,会弹出默认浏览器的下拉菜单,如 图 。
图. 默认弹出菜单
桌面控件的下拉菜单应该是可以自定义的,为了让 Google Map 控件更加贴近 SWT 桌面控件,并且防止用户点击下拉菜单的选项而引起误操作,需要屏蔽默认的 Browser 右键弹出菜单。
public class Test {
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Slashdot");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window's contents
*
* @param shell
* the main window
*/
private void createContents(Shell shell) {
shell.setLayout(new FillLayout());
// Create a web browser
final Browser browser = new Browser(shell, SWT.NONE);
browser.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent arg0) {
}
public void mouseDown(MouseEvent event) {
if (event.button == 3)
browser.execute("document.oncontextmenu = function() {return false;}");
}
public void mouseUp(MouseEvent arg0) {
}
});
browser.setUrl("http://www.baidu.com");
// browser.execute("alert('aaaaa')");
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new Test().run();
}
}
为 Browser 控件添加鼠标事件监听,在 mouseDown 中处理鼠标单击事件,event.button == 3 代表右击操作。如果是鼠标右击事件,browser 执行脚本:document.oncontextmenu = function() {return false;},这段 JS 脚本可以阻止浏览器的当前网页弹出右键菜单。