Create Menu Bar in SWT
This section illustrates you how to create a menu bar.
In SWT, the classes Menu and MenuItem of package org.eclipse.swt.widgets is
allowed to create a menu bar. The method setMenu() sets the pull down
menu. The SWT.SEPERATOR separates the items of the menu. To perform
an action on exitItem, the MenuItemListener class is called.
Following code close the shell on clicking the exit item:
if (((MenuItem) event.widget).getText().equals("Exit")) {
shell.close();
}
|
Here is the code of MenuExample.java
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.widgets.*;
public class MenuExample {
Display display;
Shell shell;
Menu menu, fileMenu, editMenu,
viewMenu;
public MenuExample() {
display = new Display();
shell = new Shell(display);
shell.setText("Menu Example");
shell.setSize(300, 200);
menu = new Menu(shell, SWT.BAR);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setText("File");
MenuItem editItem = new MenuItem(menu, SWT.CASCADE);
editItem.setText("Edit");
MenuItem viewItem = new MenuItem(menu, SWT.CASCADE);
viewItem.setText("View");
MenuItem helpItem = new MenuItem(menu, SWT.CASCADE);
helpItem.setText("Help");
Menu fileMenu = new Menu(menu);
fileItem.setMenu(fileMenu);
MenuItem newItem = new MenuItem(fileMenu, SWT.NONE);
newItem.setText("New");
MenuItem openItem = new MenuItem(fileMenu, SWT.NONE);
openItem.setText("Open...");
MenuItem saveItem = new MenuItem(fileMenu, SWT.NONE);
saveItem.setText("Save");
MenuItem saveAsItem = new MenuItem(fileMenu, SWT.NONE);
saveAsItem.setText("Save As...");
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem pageSetupItem = new MenuItem(fileMenu, SWT.NONE);
pageSetupItem.setText("Page Setup...");
MenuItem printItem = new MenuItem(fileMenu, SWT.NONE);
printItem.setText("Print...");
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitItem = new MenuItem(fileMenu, SWT.NONE);
exitItem.setText("Exit");
Menu editMenu = new Menu(menu);
editItem.setMenu(editMenu);
MenuItem cutItem = new MenuItem(editMenu, SWT.NONE);
cutItem.setText("Cut");
MenuItem pasteItem = new MenuItem(editMenu, SWT.NONE);
pasteItem.setText("Paste");
Menu viewMenu = new Menu(menu);
viewItem.setMenu(viewMenu);
MenuItem toolItem = new MenuItem(viewMenu, SWT.NONE);
toolItem.setText("ToolBars");
MenuItem fontItem = new MenuItem(viewMenu, SWT.NONE);
fontItem.setText("Font");
exitItem.addSelectionListener(new MenuItemListener());
shell.setMenuBar(menu);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
class MenuItemListener extends SelectionAdapter {
public void widgetSelected(SelectionEvent event) {
if (((MenuItem) event.widget).getText().equals("Exit")) {
shell.close();
}
}
}
public static void main(String[] args) {
MenuExample example = new MenuExample();
}
}
|
Output will be displayed as:
Download Source Code