下面列出了怎么用org.eclipse.swt.widgets.MenuItem的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@inheritDoc}
*/
@Override
protected Control createContents(Composite parent) {
final Composite fieldEditorParent = (Composite) super.createContents(parent);
final GitRepositoryPreferencePageView view = new GitRepositoryPreferencePageView(fieldEditorParent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(view);
tableViewer = view.getTableViewer();
tableViewer.setContentProvider(new ArrayContentProvider());
view.getColumnRepository().setLabelProvider(new RepositoryColumnLabelProvider());
view.getColumnLocalPath().setLabelProvider(new LocalPathColumnLabelProvider());
view.getColumnMemory().setLabelProvider(new MemoryColumnLabelProvider());
tableViewer.setInput(getGitRepositoryPaths(configuration.getGitRepositoryFolder()));
final MenuItem item = view.getMenuItemGoToRepository();
item.setEnabled(!tableViewer.getSelection().isEmpty());
item.addListener(SWT.Selection, e -> openRepositoryOnSelection(tableViewer));
tableViewer.addSelectionChangedListener(e -> item.setEnabled(!e.getSelection().isEmpty()));
return fieldEditorParent;
}
private static void click(final MenuItem menuItem) {
final Event event = new Event();
event.time = (int) System.currentTimeMillis();
event.widget = menuItem;
event.display = menuItem.getDisplay();
event.type = SWT.Selection;
UIThreadRunnable.asyncExec(
menuItem.getDisplay(),
new VoidResult() {
@Override
public void run() {
menuItem.notifyListeners(SWT.Selection, event);
}
});
}
public static IMenuItemProvider ungroupColumnsMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem columnStyleEditor = new MenuItem(popupMenu, SWT.PUSH);
columnStyleEditor.setText("Ungroup columns");
columnStyleEditor.setEnabled(true);
columnStyleEditor.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
natTable.doCommand(new UngroupColumnCommand());
}
});
}
};
}
private void populateMenuItems( )
{
for ( int i = 0; i < menu.getItemCount( ); i++ )
{
menu.getItem( i ).dispose( );
i--;
}
String[] types = this.provider.getMenuItems( );
for ( int i = 0; i < types.length; i++ )
{
MenuItem item = new MenuItem( menu, SWT.PUSH );
item.setText( provider.getMenuItemText( types[i] ) );
item.setData( types[i] );
item.setImage( this.provider.getMenuItemImage( types[i] ) );
item.addSelectionListener( listener );
}
if ( menu.getItemCount( ) <= 0 )
{
button.setDropDownMenu( null );
}
button.setText( provider.getButtonText( ) );
refresh( );
}
public static IMenuItemProvider showAllColumnMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, Menu popupMenu) {
MenuItem showAllColumns = new MenuItem(popupMenu, SWT.PUSH);
showAllColumns.setText("Show all columns");
showAllColumns.setImage(GUIHelper.getImage("show_column"));
showAllColumns.setEnabled(true);
showAllColumns.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
natTable.doCommand(new ShowAllColumnsCommand());
}
});
}
};
}
public Menu getDefaultMenu() {
Menu menu = new Menu(sText.getShell());
MenuItem cut = new MenuItem(menu, SWT.NONE);
cut.setText(XViewerText.get("menu.cut")); //$NON-NLS-1$
cut.addListener(SWT.Selection, e-> {
sText.cut();
sText.redraw();
});
MenuItem copy = new MenuItem(menu, SWT.NONE);
copy.setText(XViewerText.get("menu.copy")); //$NON-NLS-1$
copy.addListener(SWT.Selection, e-> sText.copy());
MenuItem paste = new MenuItem(menu, SWT.NONE);
paste.setText(XViewerText.get("menu.paste")); //$NON-NLS-1$
paste.addListener(SWT.Selection, e-> {
sText.paste();
sText.redraw();
});
return menu;
}
public static IMenuItemProvider columnChooserMenuItemProvider(final String menuLabel) {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem columnChooser = new MenuItem(popupMenu, SWT.PUSH);
columnChooser.setText(menuLabel);
columnChooser.setImage(GUIHelper.getImage("column_chooser"));
columnChooser.setEnabled(true);
columnChooser.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
natTable.doCommand(new DisplayColumnChooserCommand(natTable));
}
});
}
};
}
/**
* Sets the current View to the first available view for the specified
* DataSource.
*
* @param dataSource
* The DataSource whose first available View will be displayed.
*/
public void setToFirstView(DataSource dataSource) {
// Get the view menu's MenuItem associated with this data source.
MenuItem dataSourceItem = dataSourceItems.get(dataSource);
// Only proceed if the item exists.
if (dataSourceItem != null) {
// Get the Menu of views for this data source.
Menu menu = dataSourceItem.getMenu();
// Only proceed if the menu actually has items.
if (menu.getItemCount() > 0) {
// Get the view name of the first item.
String viewName = menu.getItem(0).getText();
// Set the active view.
setActiveView(dataSource + "-" + viewName);
}
}
return;
}
public static IMenuItemProvider autoResizeColumnMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem autoResizeColumns = new MenuItem(popupMenu, SWT.PUSH);
autoResizeColumns.setText("Auto resize column");
autoResizeColumns.setImage(GUIHelper.getImage("auto_resize"));
autoResizeColumns.setEnabled(true);
autoResizeColumns.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
int columnPosition = getNatEventData(event).getColumnPosition();
natTable.doCommand(new InitializeAutoResizeColumnsCommand(natTable, columnPosition, natTable.getConfigRegistry(), new GC(natTable)));
}
});
}
};
}
public static IMenuItemProvider categoriesBasedColumnChooserMenuItemProvider(final String menuLabel) {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem columnChooser = new MenuItem(popupMenu, SWT.PUSH);
columnChooser.setText(menuLabel);
columnChooser.setImage(GUIHelper.getImage("column_categories_chooser"));
columnChooser.setEnabled(true);
columnChooser.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
natTable.doCommand(new ChooseColumnsFromCategoriesCommand(natTable));
}
});
}
};
}
/**
* Checks if the context menu item matching the text nodes is enabled.
*
* @param bot a SWTBot class that wraps a {@link Widget} which extends {@link Control}. E.g.
* {@link SWTBotTree}.
* @param nodes the nodes of the context menu e.g New, Class
* @return <tt>true</tt> if the context menu item is enabled, <tt>false</tt> otherwise
* @throws WidgetNotFoundException if the widget is not found.
*/
public static boolean isContextMenuEnabled(
final AbstractSWTBot<? extends Control> bot, final String... nodes) {
final MenuItem menuItem = getMenuItemWithRegEx(bot, quote(nodes));
// show
if (menuItem == null) {
throw new WidgetNotFoundException("could not find menu: " + Arrays.asList(nodes));
}
return UIThreadRunnable.syncExec(
new BoolResult() {
@Override
public Boolean run() {
boolean enabled = menuItem.isEnabled();
hide(menuItem.getParent());
return enabled;
}
});
}
public static MenuItem cascadingAgentMenuItem(final Menu parent, final IAgent agent, final String title,
final MenuAction... actions) {
final MenuItem result = new MenuItem(parent, SWT.CASCADE);
result.setText(title);
Image image;
if (agent instanceof SimulationAgent) {
final SimulationAgent sim = (SimulationAgent) agent;
image = GamaIcons.createTempRoundColorIcon(GamaColors.get(sim.getColor()));
} else {
image = GamaIcons.create(IGamaIcons.MENU_AGENT).image();
}
result.setImage(image);
final Menu agentMenu = new Menu(result);
result.setMenu(agentMenu);
createMenuForAgent(agentMenu, agent, agent instanceof ITopLevelAgent, true, actions);
return result;
}
/**
* @return
*/
protected Menu createMenuBar() {
Menu bar = new Menu(shell, SWT.BAR);
// file
MenuItem fileItem = new MenuItem(bar, SWT.CASCADE);
fileItem.setText("&File");
Menu submenu = new Menu(shell, SWT.DROP_DOWN);
fileItem.setMenu(submenu);
MenuItem item = new MenuItem(submenu, SWT.PUSH);
item.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
}
});
item.setText("Select &All\tCtrl+A");
item.setAccelerator(SWT.MOD1 + 'A');
// edit
MenuItem editItem = new MenuItem(bar, SWT.CASCADE);
editItem.setText("&Edit");
// search
MenuItem searchItem = new MenuItem(bar, SWT.CASCADE);
searchItem.setText("&Search");
return bar;
}
@BeforeClass
public static void beforeClass() throws Exception {
RCPTestSetupHelper.beforeClass();
// Force shell activation to counter, no active Shell when running SWTBot tests in Xvfb/Xvnc
// see https://wiki.eclipse.org/SWTBot/Troubleshooting#No_active_Shell_when_running_SWTBot_tests_in_Xvfb
Display.getDefault().syncExec(new Runnable() {
public void run() {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().forceActive();
}
});
bot = new SWTWorkbenchBot();
// Wait for the Toolbox shell to be available
final Matcher<Shell> withText = withText("TLA+ Toolbox");
bot.waitUntil(Conditions.waitForShell(withText), 30000);
// Wait for the Toolbox UI to be fully started.
final Matcher<MenuItem> withMnemonic = WidgetMatcherFactory.withMnemonic("File");
final Matcher<MenuItem> matcher = WidgetMatcherFactory.allOf(WidgetMatcherFactory.widgetOfType(MenuItem.class),
withMnemonic);
bot.waitUntil(Conditions.waitForMenu(bot.shell("TLA+ Toolbox"), matcher), 30000);
}
private void createDetectorMenuItem(final String prefValue, String label) {
final MenuItem menuItem = new MenuItem(popupMenu, SWT.RADIO);
menuItem.setText(format("Detector: " + label));
menuItem.setSelection(prefValue.equals(pref(PREF_DETECTOR)));
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean sel = ((MenuItem) e.widget).getSelection();
if (sel && !prefValue.equals(pref(PREF_DETECTOR))) {
Activator.getDefault().getPreferenceStore().setValue(PREF_DETECTOR, prefValue);
agent.getDocument().refresh();
}
}
});
}
public void installSubMenuIn(final Menu menu) {
final MenuItem builtInItem = new MenuItem(menu, SWT.CASCADE);
builtInItem.setText(getTitle());
builtInItem.setImage(getImage());
mainMenu = new Menu(builtInItem);
builtInItem.setMenu(mainMenu);
mainMenu.addListener(SWT.Show, e -> {
if (mainMenu.getItemCount() > 0) {
for (final MenuItem item : mainMenu.getItems()) {
item.dispose();
}
}
fillMenu();
});
}
private void showMenu( )
{
if ( menu != null )
{
Rectangle size = button.getBounds( );
menu.setLocation( button.toDisplay( new Point( 0, size.height - 1 ) ) );
for ( int i = 0; i < menu.getItemCount( ); i++ )
{
MenuItem item = menu.getItem( i );
if ( item.getData( ).equals( getExpressionType( ) ) )
item.setSelection( true );
else
item.setSelection( false );
}
menu.setVisible( true );
}
}
public static void setMenuName(final MenuItem item, final String text) {
Display.getDefault().syncExec(
new Runnable() {
public void run() {
item.setText(text);
}
}
);
}
public void setUndoMenu( IUndo undoInterface ) {
// Grab the undo and redo menu items...
//
MenuItem undoItem = mainMenuWidgets.findMenuItem( ID_MAIN_MENU_EDIT_UNDO );
MenuItem redoItem = mainMenuWidgets.findMenuItem( ID_MAIN_MENU_EDIT_REDO );
if ( undoItem == null || redoItem == null ) {
return;
}
ChangeAction prev = null;
ChangeAction next = null;
if ( undoInterface != null ) {
prev = undoInterface.viewThisUndo();
next = undoInterface.viewNextUndo();
}
undoItem.setEnabled( prev != null );
if ( prev == null ) {
undoItem.setText( UNDO_UNAVAILABLE );
} else {
undoItem.setText( BaseMessages.getString( PKG, "HopGui.Menu.Undo.Available", prev.toString() ) );
}
KeyboardShortcut undoShortcut = mainMenuWidgets.findKeyboardShortcut( ID_MAIN_MENU_EDIT_UNDO );
if ( undoShortcut != null ) {
GuiMenuWidgets.appendShortCut( undoItem, undoShortcut );
}
redoItem.setEnabled( next != null );
if ( next == null ) {
redoItem.setText( REDO_UNAVAILABLE );
} else {
redoItem.setText( BaseMessages.getString( PKG, "HopGui.Menu.Redo.Available", next.toString() ) );
}
KeyboardShortcut redoShortcut = mainMenuWidgets.findKeyboardShortcut( ID_MAIN_MENU_EDIT_REDO );
if ( redoShortcut != null ) {
GuiMenuWidgets.appendShortCut( redoItem, redoShortcut );
}
}
public void reset() {
if (mainMenu != null && !mainMenu.isDisposed()) {
for (final MenuItem item : mainMenu.getItems()) {
item.dispose();
}
}
}
/**
* @param menu
*/
private void createUsedIn(final Menu menu) {
final MenuItem usedIn = new MenuItem(menu, SWT.CASCADE);
usedIn.setText(" Imported in...");
usedIn.setImage(GamaIcons.create("imported.in").image());
final Menu sub = new Menu(usedIn);
usedIn.setMenu(sub);
sub.addListener(SWT.Show, e -> {
for (final MenuItem item : sub.getItems()) {
item.dispose();
}
createImportedSubMenu(sub, getEditor());
});
}
public void setEnabled(boolean enabled) {
for (int i = 0; i < fItems.length; i++) {
MenuItem e = fItems[i];
if (e != null) {
e.setEnabled(enabled);
}
}
}
/**
* Adds a new spec to the toolbox, opens it and tests if parsing is done on
* a non-UI thread
*
* @see Bug #103 in general/bugzilla/index.html
*/
@Test
@Ignore
public void parseSpecInNonUIThread() {
// Open specA
SWTBotMenu fileMenu = bot.menu("File");
SWTBotMenu openSpecMenu = fileMenu.menu("Open Spec");
SWTBotMenu addNewSpecMenu = openSpecMenu.menu("Add New Spec...");
addNewSpecMenu.click();
bot.textWithLabel("Root-module file:").setText(specB);
bot.button("Finish").click();
assertNoBackendCodeInUIThread();
// Open specB
addNewSpecMenu.click();
bot.textWithLabel("Root-module file:").setText(specA);
bot.button("Finish").click();
assertNoBackendCodeInUIThread();
final String specName = getSpecName(new File(specB));
// increase timeout since farsite spec takes a long time to parse
final long timeout = SWTBotPreferences.TIMEOUT * 4;
// specs are created in non-UI thread asynchronously which causes a
// delay before the menu entry becomes available
bot.waitUntil(Conditions.waitForMenu(waitForToolboxShell(), WithText.<MenuItem> withText(specName)), timeout);
// Go back to previous spec
openSpecMenu.menu(specName);
assertNoBackendCodeInUIThread();
}
private static void createMenuEntries(Menu menu, String... labels) {
for (final String label : labels) {
final MenuItem item = new MenuItem(menu, SWT.PUSH);
item.setText(label);
item.addListener(SWT.Selection, e -> System.out.println("Click on menu item [" + label + "]"));
}
}
public void createMenu(Shell shell) {
Menu bar = new Menu(shell, SWT.BAR);
shell.setMenuBar(bar);
MenuItem fileItem = new MenuItem(bar, SWT.CASCADE);
fileItem.setText("&File");
Menu submenu = new Menu(shell, SWT.DROP_DOWN);
fileItem.setMenu(submenu);
MenuItem item = new MenuItem(submenu, SWT.PUSH);
item.addListener(SWT.Selection, e -> Runtime.getRuntime().halt(0));
item.setText("E&xit\tCtrl+W");
item.setAccelerator(SWT.MOD1 + 'W');
}
/** Creates a menu entry which indicates that no contacts with Saros are online. */
private MenuItem createInvalidContactsMenuItem(Menu parentMenu, int index) {
MenuItem menuItem = new MenuItem(parentMenu, SWT.NONE, index);
menuItem.setText(Messages.SessionWithContacts_menuItem_no_contacts_available_text);
menuItem.setEnabled(false);
return menuItem;
}
@SuppressWarnings("unused")
private void selectConnectAccount(String baseJID) throws RemoteException {
SWTBotToolbarDropDownButton b = view.toolbarDropDownButton(TB_CONNECT);
@SuppressWarnings("static-access")
Matcher<MenuItem> withRegex = WidgetMatcherFactory.withRegex(Pattern.quote(baseJID) + ".*");
b.menuItem(withRegex).click();
try {
b.pressShortcut(KeyStroke.getInstance("ESC"));
} catch (ParseException e) {
log.debug("", e);
}
}
private void appendShortcut(ParameterizedCommand parameterizedCommand, MenuItem item) {
TriggerSequence triggerSequence = eBindingService.getBestSequenceFor(parameterizedCommand);
if (triggerSequence != null && triggerSequence instanceof KeySequence) {
KeySequence keySequence = (KeySequence) triggerSequence;
String rawLabel = item.getText();
item.setText(String.format("%s %s%s", rawLabel, '\t', keySequence.format()));
}
}
/** Creates a menu entry which indicates that no Saros enabled contacts are online. */
private MenuItem createNoProjectsMenuItem(final Menu parentMenu, final int index) {
final MenuItem menuItem = new MenuItem(parentMenu, SWT.NONE, index);
menuItem.setText(Messages.SessionWithProjects_no_projects_in_workspace);
menuItem.setEnabled(false);
return menuItem;
}
public void createViewSelectedCellMenuItem(Menu popupMenu) {
setupActions();
final MenuItem item = new MenuItem(popupMenu, SWT.CASCADE);
item.setText(XViewerText.get("menu.copy_celldata")); //$NON-NLS-1$
item.addListener(SWT.Selection, e->copySelectedCell.run());
final MenuItem item1 = new MenuItem(popupMenu, SWT.CASCADE);
item1.setText(XViewerText.get("menu.view_celldata")); //$NON-NLS-1$
item1.addListener(SWT.Selection, e->viewSelectedCell.run());
}