Coding Tips (JavaScript/CSS/VBA/Win32)
Useful code snippets, tips and some Windows applications
Creating a Menu
To create a menu, add the following code to the main method before the shell.open() statement.
//create the menu bar Menu menu = new Menu(shell, SWT.BAR); shell.setMenuBar(menu); // add File option to it MenuItem file = new MenuItem(menu, SWT.CASCADE); file.setText("File"); //set the menu for the File option Menu filemenu = new Menu(shell, SWT.DROP_DOWN); file.setMenu(filemenu); //add MenuItems to the File menu MenuItem actionItem = new MenuItem(filemenu, SWT.PUSH); actionItem.setText("Exit"); actionItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { display.dispose(); } });
When you click on the File-Exit menu item, the application will actually exit the screen.
Let's add an About menu to the application. The About menu will have to Menu items: Help and About. These buttons won't do anything useful at the moment. We'll get to that later.
//add About menu MenuItem about = new MenuItem(menu, SWT.CASCADE); about.setText("About"); //set the menu for the About option Menu aboutmenu = new Menu(shell, SWT.DROP_DOWN); about.setMenu(aboutmenu); //add MenuItems to the About menu MenuItem actionItem2 = new MenuItem(aboutmenu, SWT.PUSH); actionItem2.setText("Help"); MenuItem actionItem3 = new MenuItem(aboutmenu, SWT.PUSH); actionItem3.setText("About");
The resulting application looks like this:
Previous --- Next - Adding Controls