创建菜单时,需要先new一个Menu出来,然后把它和shell连接到一直。如下程序:
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
public class MenuShell {
Display d;
Shell s;
MenuShell( ) {
d = new Display( );
s = new Shell(d);
s.setSize(300,300);
s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
s.setText("A Shell Menu Example");
Menu m = new Menu(s,SWT.BAR );
// create a File menu and add an Exit item
final MenuItem file = new MenuItem(m, SWT.CASCADE);
file.setText("File");
final Menu filemenu = new Menu(s, SWT.DROP_DOWN);
file.setMenu(filemenu);
final MenuItem openItem = new MenuItem(filemenu, SWT.PUSH);
openItem.setText("Open");
final MenuItem separator = new MenuItem(filemenu, SWT.SEPARATOR);
final MenuItem exitItem = new MenuItem(filemenu, SWT.PUSH);
exitItem.setText("Exit");
// create an Edit menu and add Cut, Copy, and Paste items
final MenuItem edit = new MenuItem(m, SWT.CASCADE);
edit.setText("Edit");
final Menu editmenu = new Menu(s, SWT.DROP_DOWN);
edit.setMenu(editmenu);
final MenuItem cutItem = new MenuItem(editmenu, SWT.PUSH);
cutItem.setText("Cut");
final MenuItem copyItem = new MenuItem(editmenu, SWT.PUSH);
copyItem.setText("Copy");
final MenuItem pasteItem = new MenuItem(editmenu, SWT.PUSH);
pasteItem.setText("Paste");
//create a Window menu and add Child items
final MenuItem window = new MenuItem(m, SWT.CASCADE);
window.setText("Window");
final Menu windowmenu = new Menu(s, SWT.DROP_DOWN);
window.setMenu(windowmenu);
final MenuItem maxItem = new MenuItem(windowmenu, SWT.PUSH);
maxItem.setText("Maximize");
final MenuItem minItem = new MenuItem(windowmenu, SWT.PUSH);
minItem.setText("Minimize");
// create a Help menu and add an About item
final MenuItem help = new MenuItem(m, SWT.CASCADE);
help.setText("Help");
final Menu helpmenu = new Menu(s, SWT.DROP_DOWN);
help.setMenu(helpmenu);
final MenuItem aboutItem = new MenuItem(helpmenu, SWT.PUSH);
aboutItem.setText("About");
s.setMenuBar(m);
s.open( );
while(!s.isDisposed( )){
if(!d.readAndDispatch( ))
d.sleep( );
}
d.dispose( );
}
public static void main(String[] args) {
MenuShell s = new MenuShell();
}
}
运行上述代码后得到的显示界面如图所示。