Java Code Examples for javax.swing.Action

The following are top voted examples for showing how to use javax.swing.Action. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: LabelVarsFilter.java   Source Code and License 7 votes vote down vote up
public Action[] getActions(NodeActionsProvider original, Object node) throws UnknownTypeException {
    Action [] actions = original.getActions (node);
    if (node instanceof ObjectVariable) {
        int index;
        for (index = 0; index < actions.length; index++) {
            if (actions[index] == null)
                break;
        }
        Action[] newActions = new Action[actions.length + 1];
        System.arraycopy(actions, 0, newActions, 0, index);
        newActions[index] = MARK_OBJECT_ACTION;
        if (index < actions.length) {
            System.arraycopy(actions, index, newActions, index + 1, actions.length - index);
        }
        actions = newActions;
    }
    return actions;
}
 
Example 2
Project: incubator-netbeans   File: RepositoryRevision.java   Source Code and License 6 votes vote down vote up
@NbBundle.Messages({
    "CTL_Action.ViewCurrent.name=View Current"
})
Action[] getActions () {
    List<Action> actions = new ArrayList<Action>();
    boolean viewEnabled = getFile() != null && getChangedPath().getAction() != HgLogMessage.HgDelStatus;
    if (getFile() != null) {
        actions.add(new AbstractAction(NbBundle.getMessage(RepositoryRevision.class, "CTL_SummaryView_RollbackTo", getLogInfoHeader().getLog().getRevisionNumber())) { // NOI18N
            @Override
            public void actionPerformed(ActionEvent e) {
                revertModifications();
            }                
        });
    }
    if (viewEnabled) {
        actions.add(new AbstractAction(NbBundle.getMessage(RepositoryRevision.class, "CTL_SummaryView_View")) { //NOI18N
 
Example 3
Project: incubator-netbeans   File: AbstractEditorAction.java   Source Code and License 6 votes vote down vote up
@Override
public final Object getValue(String key) {
    Action dAction = delegateAction;
    // Delegate whole getValue() if delegateAction already exists
    if (dAction != null && dAction != UNITIALIZED_ACTION) {
        Object value = dAction.getValue(key);
        if (value == null) {
            value = getValueLocal(key);
            if (value != null) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("Transfer wrapper action property: key=" + key + ", value=" + value + '\n'); // NOI18N
                }
                dAction.putValue(key, value);
            }
        }
        return value;
    }

    return getValueLocal(key);
}
 
Example 4
Project: incubator-netbeans   File: VCSHistoryTest.java   Source Code and License 6 votes vote down vote up
public void testHistoryEntryEditable() throws IOException {
    MessageEditProviderImpl provider = new MessageEditProviderImpl();
    provider.message = null;
    VCSHistoryProvider.HistoryEntry h = 
            new VCSHistoryProvider.HistoryEntry(
                new File[] {new File("")}, 
                new Date(System.currentTimeMillis()), 
                "msg", 
                "user", 
                "username", 
                "12345", 
                "1234567890", 
                new Action[0], 
                null,
                provider);
    assertTrue(h.canEdit());
    h.setMessage("msg2");
    assertEquals("msg2", provider.message);
}
 
Example 5
Project: incubator-netbeans   File: ProfilerTableActions.java   Source Code and License 6 votes vote down vote up
private Action selectNextColumnAction() {
    return new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            ProfilerColumnModel cModel = table._getColumnModel();
            if (table.getRowCount() == 0 || cModel.getVisibleColumnCount() == 0) return;
            
            int column = table.getSelectedColumn();
            if (column == -1) {
                table.selectColumn(cModel.getFirstVisibleColumn(), false);
                table.selectRow(0, true);
            } else {
                int nextColumn = cModel.getNextVisibleColumn(column);
                if (nextColumn > column) table.selectColumn(nextColumn, true);
            }
        }
    };
}
 
Example 6
Project: incubator-netbeans   File: ShelveChangesAction.java   Source Code and License 6 votes vote down vote up
public static ShelveChangesActionProvider getProvider () {
    if (ACTION_PROVIDER == null) {
        ACTION_PROVIDER = new ShelveChangesActionProvider() {
            @Override
            public Action getAction () {
                Action a = SystemAction.get(SaveStashAction.class);
                Utils.setAcceleratorBindings("Actions/Git", a); //NOI18N
                return a;
            }

            @Override
            public JComponent[] getUnshelveActions (VCSContext ctx, boolean popup) {
                JComponent[] cont = UnshelveMenu.getInstance().getMenu(ctx, popup);
                if (cont == null) {
                    cont = super.getUnshelveActions(ctx, popup);
                }
                return cont;
            }
            
        };
    }
    return ACTION_PROVIDER;
}
 
Example 7
Project: incubator-netbeans   File: AbstractMultiViewTopComponentTestCase.java   Source Code and License 6 votes vote down vote up
public void testGetLookup() throws Exception {
    final MVElem elem1 = new MVElem(new Action[] {new Act1("act1")} );
    final MVElem elem2 = new MVElem(new Action[] {new Act1("act2")} );
    MultiViewDescription desc1 = new MVDesc("desc1", null, 0, elem1);
    MultiViewDescription desc2 = new MVDesc("desc2", null, 0, elem2);
    MultiViewDescription[] descs = new MultiViewDescription[] { desc1, desc2 };
    TopComponent tc = callFactory(descs, desc2);
    
    tc.open();
    Object result = tc.getLookup().lookup(MVElem.class);
    assertNotNull(result);
    assertEquals(result, elem2);
    MultiViewHandler hand = MultiViews.findMultiViewHandler(tc);
    
    hand.requestActive(Accessor.DEFAULT.createPerspective(desc1));
    result = tc.getLookup().lookup(MVElem.class);
    assertNotNull(result);
    assertEquals(result, elem1);
    
}
 
Example 8
Project: incubator-netbeans   File: EditablePropertyDisplayer.java   Source Code and License 6 votes vote down vote up
Action getCustomEditorAction() {
    if (customEditorAction == null) {
        PropertyModel mdl = null;

        if (modelRef != null) {
            mdl = modelRef.get();
        }

        customEditorAction = new CustomEditorAction(new Invoker(), mdl);

        getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
            KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_DOWN_MASK, false), "invokeCustomEditor"
        ); //NOI18N

        //XXX this could be done lazily
        getActionMap().put("invokeCustomEditor", customEditorAction); //NOI18N

        //            System.err.println("Installed custom editor action");
    }

    return customEditorAction;
}
 
Example 9
Project: incubator-netbeans   File: ContextManagerTest.java   Source Code and License 6 votes vote down vote up
@RandomlyFails
public void testListenerGCedAfterActionGCed () throws Exception {
    InstanceContent ic = new InstanceContent();
    lkp = new AbstractLookup(ic);
    Lookup.Result<Integer> lookupResult = lkp.lookupResult(Integer.class);

    Action action = ((ContextAwareAction) Actions.forID("cat", "survive")).createContextAwareInstance(lkp);
    Action fallbackAction = ((GeneralAction.DelegateAction) action).fallback;
    WeakReference<Action> fallbackActionRef = new WeakReference<Action>(fallbackAction);
    WeakReference<Action> clone = new WeakReference<Action>(action);
    cm = ContextManager.findManager(lkp, true);
    WeakReference lsetRef = new WeakReference<Object>(cm.findLSet(Integer.class));

    // both delegate and delegating actions are GCed before WeakListenerSupport is triggered in ActiveRefQueue:
    // fallbackAction.removePropertyChangeListener(delegating.weakL);
    fallbackAction = null;
    action = null;
    assertGC("Action should be GCed", clone);

    assertGC("Fallback action should be GCed", fallbackActionRef);
    assertGC("Action LSet Should be GCed", lsetRef);
    lookupResult.allInstances();
}
 
Example 10
Project: incubator-netbeans   File: CslTestBase.java   Source Code and License 6 votes vote down vote up
protected void initializeRegistry() {
    DefaultLanguageConfig defaultLanguage = getPreferredLanguage();
    if (defaultLanguage == null) {
        fail("If you don't implement getPreferredLanguage(), you must override initializeRegistry!");
        return;
    }
    if (!LanguageRegistry.getInstance().isSupported(getPreferredMimeType())) {
        List<Action> actions = Collections.emptyList();
        org.netbeans.modules.csl.core.Language dl = new org.netbeans.modules.csl.core.Language(
                "unknown", getPreferredMimeType(), actions,
                defaultLanguage, getCodeCompleter(),
                getRenameHandler(), defaultLanguage.getDeclarationFinder(),
                defaultLanguage.getFormatter(), getKeystrokeHandler(),
                getIndexerFactory(), getStructureScanner(), null,
                defaultLanguage.isUsingCustomEditorKit());
        List<org.netbeans.modules.csl.core.Language> languages = new ArrayList<org.netbeans.modules.csl.core.Language>();
        languages.add(dl);
        CslCorePackageAccessor.get().languageRegistryAddLanguages(languages);
    }
}
 
Example 11
Project: incubator-netbeans   File: MergeAction.java   Source Code and License 6 votes vote down vote up
Action getDelegateAction() {
    Action result = null;
    synchronized (this) {
        result = delegateAction;
        if (result == null || !result.isEnabled()) {
            if (attached()) {
                result = updateDelegateAction();
            } else {
                result = findEnabledAction();
            }
        }
    }
    if (result == null) {
        result = actions[0];
    }
    return result;
}
 
Example 12
Project: VASSAL-src   File: ModuleManagerWindow.java   Source Code and License 6 votes vote down vote up
@Override
public JPopupMenu buildPopup(int row) {
  final JPopupMenu m = new JPopupMenu();
  final Action playAction = new Player.LaunchAction(ModuleManagerWindow.this, file);
  playAction.setEnabled(!Info.isModuleTooNew(metadata.getVassalVersion()));
  m.add(playAction);
  final Action editAction = new Editor.ListLaunchAction(ModuleManagerWindow.this, file);
  editAction.setEnabled(!Info.isModuleTooNew(metadata.getVassalVersion()));
  m.add(editAction);
  m.add(new AbstractAction(Resources.getString("General.remove")) {
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent e) {
      removeModule(file);
      cleanupTileCache();
    }
  });

  m.addSeparator();
  m.add(addFolderAction);
  m.addSeparator();
  m.add(newExtensionAction);
  m.add(addExtensionAction);
  return m;
}
 
Example 13
Project: incubator-netbeans   File: RuntimeComboBox.java   Source Code and License 6 votes vote down vote up
@Override
public void setSelectedItem(final Object anItem) {
    if (anItem != null) {
        if (anItem.equals(SEPARATOR)) return;
        if (anItem instanceof Action) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    ((Action)anItem).actionPerformed(new ActionEvent(this, 0, "grow")); //NOI18N
                }
            });
            
        } else {
            selected = (T)anItem;
        }
    }
}
 
Example 14
Project: incubator-netbeans   File: TextRegionManager.java   Source Code and License 6 votes vote down vote up
public void actionPerformed(ActionEvent evt) {
    TextRegionManager manager = textRegionManager(evt);
    if (manager != null) {
        switch (actionType) {
            case TAB:
                manager.tabAction();
                break;
            case SHIFT_TAB:
                manager.shiftTabAction();
                break;
            case ENTER:
                if (!manager.enterAction()) {
                    Action original = (Action)getValue(ORIGINAL_ACTION_PROPERTY);
                    if (original != null)
                        original.actionPerformed(evt);
                }
                break;
        }
    }
}
 
Example 15
Project: incubator-netbeans   File: DefaultAWTBridgeTest.java   Source Code and License 6 votes vote down vote up
public void testHideWhenDisabled() throws Exception {
    class NoOpAction extends AbstractAction {
        NoOpAction(String n) {
            super(n);
        }
        public @Override void actionPerformed(ActionEvent e) {}
    }
    Action a = new NoOpAction("a1");
    assertEquals(Collections.singletonList("a1"), popupMenu(a));
    a = new NoOpAction("a2");
    a.setEnabled(false);
    assertEquals(Collections.singletonList("a2[disabled]"), popupMenu(a));
    a = new NoOpAction("a3");
    a.putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
    assertEquals(Collections.singletonList("a3"), popupMenu(a));
    a = new NoOpAction("a4");
    a.putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
    a.setEnabled(false);
    assertEquals(Collections.emptyList(), popupMenu(a));
}
 
Example 16
Project: incubator-netbeans   File: ExecJSAction.java   Source Code and License 5 votes vote down vote up
protected ExecJSAction(String name) {
    putValue(Action.NAME, name);
    js = null;
    NashornPlatform.getDefault().addChangeListener(WeakListeners.change(this, NashornPlatform.getDefault()));
    JavaPlatform platform = NashornPlatform.getDefault().getPlatform();
    setEnabled(platform != null);
}
 
Example 17
Project: incubator-netbeans   File: DockerNode.java   Source Code and License 5 votes vote down vote up
@Override
public Action[] getActions(boolean context) {
    List<Action> ret = new ArrayList<>();
    ret.addAll(Utilities.actionsForPath("Docker/Wizard")); // NOI18N
    ret.add(null);
    ret.addAll(Utilities.actionsForPath("Docker/Credentials")); // NOI18N
    return ret.toArray(new Action[ret.size()]);
}
 
Example 18
Project: SER316-Dresden   File: HTMLEditor.java   Source Code and License 5 votes vote down vote up
public RedoAction() {
    super(Local.getString("Redo"));
    setEnabled(false);
    putValue(
        Action.SMALL_ICON,
        new ImageIcon(cl.getResource("/htmleditor/icons/redo16.png")));
    putValue(
        Action.ACCELERATOR_KEY,
        KeyStroke.getKeyStroke(
            KeyEvent.VK_Z,
            KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK));
}
 
Example 19
Project: incubator-netbeans   File: DerbyDatabaseNode.java   Source Code and License 5 votes vote down vote up
@Override
public Action[] getActions(boolean context) {
    if ( context ) {
        return super.getActions(context);
    } else {
        return new SystemAction[] {
            SystemAction.get(ConnectDatabaseAction.class),
            SystemAction.get(DeleteAction.class)
        };
    }
}
 
Example 20
Project: incubator-netbeans   File: RootNode.java   Source Code and License 5 votes vote down vote up
@Override
public Action[] getActions(boolean context) {
    Action[] arr = Utilities.actionsForPath(registry.getPath()+"/Actions").toArray(new Action[0]); // NOI18N
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == null) {
            continue;
        }
        if (Boolean.TRUE.equals(arr[i].getValue("serverNodeHidden"))) { // NOI18N
            arr[i] = null;
        }
    }
    return arr;
}
 
Example 21
Project: incubator-netbeans   File: BIEditorSupport.java   Source Code and License 5 votes vote down vote up
final CloseOperationState canCloseElement(TopComponent tc) {
    // if this is not the last cloned java editor component, closing is OK
    if (!isLastView(tc)) {
        return CloseOperationState.STATE_OK;
    }

    if (!isModified()) {
        return CloseOperationState.STATE_OK;
    }

    AbstractAction save = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                saveDocument();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    };
    save.putValue(Action.LONG_DESCRIPTION, NbBundle.getMessage(BIEditorSupport.class, "MSG_MODIFIED", getDataObject().getPrimaryFile().getNameExt()));

    // return a placeholder state - to be sure our CloseHandler is called
    return MultiViewFactory.createUnsafeCloseState(
            "ID_BEANINFO_CLOSING", // NOI18N
            save,
            MultiViewFactory.NOOP_CLOSE_ACTION);
}
 
Example 22
Project: incubator-netbeans   File: LocalHistoryProvider.java   Source Code and License 5 votes vote down vote up
private synchronized Action[] getActions() {
    if(actions == null) {
        actions = new Action[] {
            new RevertFileAction(),
            new DeleteAction()
        };
    }
    return actions;
}
 
Example 23
Project: MaxSim   File: ActionManager.java   Source Code and License 5 votes vote down vote up
public StateChangeAction getStateChangeAction(String name)
{
    Action a = getAction(name);
    if(a instanceof StateChangeAction)
        return (StateChangeAction)a;
    else
        return null;
}
 
Example 24
Project: smile_1.5.0_java7   File: FontChooser.java   Source Code and License 5 votes vote down vote up
private JDialog createDialog(Component parent) {
    Frame frame = parent instanceof Frame ? (Frame) parent
            : (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
    JDialog dialog = new JDialog(frame, getMessage("SelectFont"), true);

    Action okAction = new DialogOKAction(dialog);
    Action cancelAction = new DialogCancelAction(dialog);

    JButton okButton = new JButton(okAction);
    okButton.setFont(DEFAULT_FONT);
    JButton cancelButton = new JButton(cancelAction);
    cancelButton.setFont(DEFAULT_FONT);

    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setLayout(new GridLayout(2, 1));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);
    buttonsPanel.setBorder(BorderFactory.createEmptyBorder(25, 0, 10, 10));

    ActionMap actionMap = buttonsPanel.getActionMap();
    actionMap.put(cancelAction.getValue(Action.DEFAULT), cancelAction);
    actionMap.put(okAction.getValue(Action.DEFAULT), okAction);
    InputMap inputMap = buttonsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), cancelAction.getValue(Action.DEFAULT));
    inputMap.put(KeyStroke.getKeyStroke("ENTER"), okAction.getValue(Action.DEFAULT));

    JPanel dialogEastPanel = new JPanel();
    dialogEastPanel.setLayout(new BorderLayout());
    dialogEastPanel.add(buttonsPanel, BorderLayout.NORTH);

    dialog.getContentPane().add(this, BorderLayout.CENTER);
    dialog.getContentPane().add(dialogEastPanel, BorderLayout.EAST);
    dialog.pack();
    dialog.setLocationRelativeTo(frame);
    return dialog;
}
 
Example 25
Project: incubator-netbeans   File: NbEditorKit.java   Source Code and License 5 votes vote down vote up
@Override
protected Action[] getDeclaredActions() {
    List<Action> declaredActionList = EditorActionsProvider.getEditorActions(getContentType());
    Action[] declaredActions = new Action[declaredActionList.size()];
    declaredActionList.toArray(declaredActions);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "Declared Actions (found ({0})): ", new Object[]{Integer.valueOf(declaredActions.length)}); // NOI18N
        for (Action a : declaredActions) {
            LOG.log(Level.FINE, "Action: {0}", new Object[]{a}); // NOI18N
        }
    }
    return declaredActions;
}
 
Example 26
Project: ramus   File: MainFrame.java   Source Code and License 5 votes vote down vote up
private JToolBar createToolBar(final Object[] os) {
    final JToolBar res = new JToolBar();
    for (final Object o : os) {
        if (o == null)
            res.addSeparator();
        else
            res.add((Action) o);
    }
    desableFocus(res);
    return res;
}
 
Example 27
Project: Reinickendorf_SER316   File: HTMLEditor.java   Source Code and License 5 votes vote down vote up
public RedoAction() {
	super(Local.getString("Redo"));
	setEnabled(false);
	putValue(
		Action.SMALL_ICON,
		new ImageIcon(cl.getResource("resources/icons/redo16.png")));
	putValue(
		Action.ACCELERATOR_KEY,
		KeyStroke.getKeyStroke(
			KeyEvent.VK_Z,
			KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK));
}
 
Example 28
Project: incubator-netbeans   File: JavaKit.java   Source Code and License 5 votes vote down vote up
@Override
protected Action[] createActions() {
    Action[] superActions = super.createActions();

    Action[] actions = new BaseAction[] {
        new PrefixMakerAction(makeGetterAction, "get", getSetIsPrefixes), // NOI18N
        new PrefixMakerAction(makeSetterAction, "set", getSetIsPrefixes), // NOI18N
        new PrefixMakerAction(makeIsAction, "is", getSetIsPrefixes), // NOI18N
        new ToggleCommentAction("//"), // NOI18N
        new JavaGenerateFoldPopupAction(), // NO_KEYBINDING in super
        new InstantRenameAction(),
        new InsertSemicolonAction(true),
        new InsertSemicolonAction(false),
        new SelectCodeElementAction(selectNextElementAction, true),
        new SelectCodeElementAction(selectPreviousElementAction, false),
        new JavaMoveCodeElementAction(EditorActionNames.moveCodeElementUp, false),
        new JavaMoveCodeElementAction(EditorActionNames.moveCodeElementDown, true),

        new FastImportAction(),
        new GoToSuperTypeAction(),

        new GoToMarkOccurrencesAction(false),
        new GoToMarkOccurrencesAction(true),
        new ClipboardHandler.JavaCutAction(),
    };
    final Action[] value = TextAction.augmentList(superActions, actions);
    
    return !INSTANT ? value : removeInstant(value);
}
 
Example 29
Project: incubator-netbeans   File: RepositoryBrowserPanel.java   Source Code and License 5 votes vote down vote up
@Override
public Action[] getPopupActions (boolean context) {
    return new Action[] {
        new AbstractAction(NbBundle.getMessage(BranchesTopNode.class, "LBL_RepositoryPanel.RefreshTagsAction.name")) { //NOI18N
            @Override
            public void actionPerformed (ActionEvent e) {
                ((TagChildren) getChildren()).refreshTags();
            }
        }
    };
}
 
Example 30
Project: incubator-netbeans   File: GuiUtil.java   Source Code and License 5 votes vote down vote up
private static void callAction(Action a, Node node, ActionEvent actionEvent) {
    if (a instanceof ContextAwareAction) {
        a = ((ContextAwareAction)a).createContextAwareInstance(node.getLookup());
    }
    if (a == null) {
        return;
    }
    a.actionPerformed(actionEvent);
}
 
Example 31
Project: incubator-netbeans   File: RepositoryBrowserPanel.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed (ActionEvent e) {
    List<Action> delegetaActions = getDeleteDelegates();
    for (Action a : delegetaActions) {
        a.actionPerformed(e);
    }
}
 
Example 32
Project: SER316-Dresden   File: HTMLEditor.java   Source Code and License 5 votes vote down vote up
protected void update() {
    if (undo.canUndo()) {
        setEnabled(true);
        putValue(
            Action.SHORT_DESCRIPTION,
            undo.getUndoPresentationName());
    } else {
        setEnabled(false);
        putValue(Action.SHORT_DESCRIPTION, Local.getString("Undo"));
    }
}
 
Example 33
Project: incubator-netbeans   File: NbEditorToolBar.java   Source Code and License 5 votes vote down vote up
/** Attempt to find the editor keystroke for the given action. */
private KeyStroke[] findEditorKeys(String editorActionName, KeyStroke defaultKey) {
    KeyStroke[] ret = new KeyStroke[] { defaultKey };
    JTextComponent comp = getComponent();
    if (editorActionName != null && comp != null) {
        TextUI textUI = comp.getUI();
        Keymap km = comp.getKeymap();
        if (textUI != null && km != null) {
            EditorKit kit = textUI.getEditorKit(comp);
            if (kit instanceof BaseKit) {
                Action a = ((BaseKit)kit).getActionByName(editorActionName);
                if (a != null) {
                    KeyStroke[] keys = km.getKeyStrokesForAction(a);
                    if (keys != null && keys.length > 0) {
                        ret = keys;
                    } else {
                        // try kit's keymap
                        Keymap km2 = ((BaseKit)kit).getKeymap();
                        KeyStroke[] keys2 = km2.getKeyStrokesForAction(a);
                        if (keys2 != null && keys2.length > 0) {
                            ret = keys2;
                        }                            
                    }
                }
            }
        }
    }
    return ret;
}
 
Example 34
Project: incubator-netbeans   File: PhysicalView.java   Source Code and License 5 votes vote down vote up
public @Override Action[] getActions(boolean context) {

            if ( context ) {
                return super.getActions( true );
            }
            else { 
                Action[] folderActions = super.getActions( false );
                Action[] projectActions;
                
                if ( isProjectDir ) {
                    if( projectDelegateNode != null ) {
                        projectActions = projectDelegateNode.getActions( false );
                    }
                    else {
                        // If this is project dir then the properties action 
                        // has to be replaced to invoke project customizer
                        projectActions = new Action[ folderActions.length ]; 
                        for ( int i = 0; i < folderActions.length; i++ ) {
                            if ( folderActions[i] instanceof org.openide.actions.PropertiesAction ) {
                                projectActions[i] = CommonProjectActions.customizeProjectAction();
                            }
                            else {
                                projectActions[i] = folderActions[i];
                            }
                        }
                    }
                }
                else {
                    projectActions = folderActions;
                }
                
                return projectActions;
            }                                            
        }
 
Example 35
Project: incubator-netbeans   File: LinkButton.java   Source Code and License 5 votes vote down vote up
/**
 * C'tor
 *
 * @param text
 * @param icon
 * @param al Action to invoke when the button is pressed, can be null but
 * the button is disabled then.
 */
public LinkButton(String text, Icon icon, Action a, boolean underlined) {
    super(text);
    this.underlined = underlined;
    setIcon(icon);
    setPressedIcon(icon);
    Object tooltip = a.getValue(Action.SHORT_DESCRIPTION);
    if (null != tooltip) {
        setToolTipText(tooltip.toString());
    }
    this.handlePopupEvents = true;
    init(a);
}
 
Example 36
Project: incubator-netbeans   File: BreakpointCustomizeAction.java   Source Code and License 5 votes vote down vote up
public Action createContextAwareInstance(Lookup actionContext) {
    Collection<? extends BreakpointAnnotation> ann = actionContext.lookupAll(BreakpointAnnotation.class);
    if (ann.size() == 1) {
        return new BreakpointAwareAction(ann.iterator().next());
    } else {
        //Exceptions.printStackTrace(new IllegalStateException("expecting BreakpointAnnotation object in lookup "+actionContext));
        return this;
    }
}
 
Example 37
Project: incubator-netbeans   File: ViewActions.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an action that opens Sessions TopComponent.
 */
public static Action createSessionsViewAction () {
    ViewActions action = new ViewActions("sessionsView");
    // When changed, update also mf-layer.xml, where are the properties duplicated because of Actions.alwaysEnabled()
    action.putValue (Action.NAME, "CTL_SessionsAction");
    action.putValue ("iconbase",
            "org/netbeans/modules/debugger/resources/sessionsView/session_16.png" // NOI18N
    );
    return action;
}
 
Example 38
Project: jaer   File: SliderToolTips.java   Source Code and License 5 votes vote down vote up
public static void postToolTip(JComponent comp){ 
    Action action = comp.getActionMap().get("postTip"); 
    if(action==null) // no tooltip 
        return; 
    ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, 
                            "postTip", EventQueue.getMostRecentEventTime(), 0); 
    action.actionPerformed(ae); 
}
 
Example 39
Project: incubator-netbeans   File: BaseNode.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the actions associated with this node.
 * 
 * @param context true if this is for a context menu, false otherwise
 * @return an array of Actions
 */
@Override
public Action[] getActions(boolean context) {
    if (context) {
        return super.getActions(true);
    }
    
    return Utilities
            .actionsForPath("Databases/Explorer/" + layerEntry + "/Actions")
            .toArray(new Action[0]);
}
 
Example 40
Project: VASSAL-src   File: ConfigureTree.java   Source Code and License 5 votes vote down vote up
protected Action buildImportAction(final Configurable target) {
  Action a = new AbstractAction("Add Imported Class") {
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent evt) {
      final Configurable child = importConfigurable();
      if (child != null) {
        try {
          child.build(null);
          final Configurable c = target;
          if (child.getConfigurer() != null) {
            PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) {
              private static final long serialVersionUID = 1L;

              public void save() {
                super.save();
                insert(c, child, getTreeNode(c).getChildCount());
              }

              public void cancel() {
                dispose();
              }
            };
            w.setVisible(true);
          }
          else {
            insert(c, child, getTreeNode(c).getChildCount());
          }
        }
        // FIXME: review error message
        catch (Exception ex) {
          JOptionPane.showMessageDialog(getTopLevelAncestor(), "Error adding " + getConfigureName(child) + " to " + getConfigureName(target) + "\n"
              + ex.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  };
  return a;
}
 
Example 41
Project: incubator-netbeans   File: ToggleDebuggingAction.java   Source Code and License 5 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup actionContext) {
    JEditorPane pane = actionContext.lookup(JEditorPane.class);
    if (pane != null) {
        return new ToggleDebuggingAction(pane);
    }
    return this;
}
 
Example 42
Project: incubator-netbeans   File: Abbrev.java   Source Code and License 5 votes vote down vote up
protected boolean doExpansion(int dotPos, String expandStr, ActionEvent evt)
throws BadLocationException {
    Object expansion = translateAbbrev(expandStr);
    boolean expanded = false;
    if (expansion instanceof String) { // expand to string
        BaseDocument doc = editorUI.getDocument();
        String ins = (String)expansion;
        int offset = ins.indexOf('|');
        if (offset >= 0) {
            if (offset > 0) doc.insertString(dotPos, ins.substring(0, offset), null);
            if (offset+1 < ins.length()) doc.insertString(dotPos + offset,
                    ins.substring(offset + 1), null);
            Caret caret = editorUI.getComponent().getCaret();
            caret.setDot(dotPos + offset);
        } else {
            doc.insertString(dotPos, ins, null);
        }

        if(ins.indexOf("\n") != -1) { // NOI18N
            Reformat formatter = Reformat.get(doc);
            formatter.lock();
            try {
                doc.atomicLock();
                try {
                    formatter.reformat(dotPos, dotPos + ins.length());
                } finally {
                    doc.atomicUnlock();
                }
            } finally {
                formatter.unlock();
            }
        }
        
        expanded = true;
    } else if (expansion instanceof Action) {
        ((Action)expansion).actionPerformed(evt);
        expanded = true;
    }
    return expanded;
}
 
Example 43
Project: incubator-netbeans   File: GeneralActionTest.java   Source Code and License 5 votes vote down vote up
private Action readAction(String fileName) throws Exception {
    FileObject fo = this.folder.getFileObject(fileName);
    assertNotNull("file " + fileName, fo);
    
    Object obj = fo.getAttribute("instanceCreate");
    assertNotNull("File object has not null instanceCreate attribute", obj);
    
    if (!(obj instanceof Action)) {
        fail("Object needs to be action: " + obj);
    }
    
    return (Action)obj;
}
 
Example 44
Project: JavaGraph   File: ResourceTab.java   Source Code and License 5 votes vote down vote up
/** Adds a key accelerator for a given action. */
private void addAccelerator(SimulatorAction action) {
    KeyStroke key = (KeyStroke) action.getValue(Action.ACCELERATOR_KEY);
    String name = (String) action.getValue(Action.NAME);
    getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, name);
    getInputMap(WHEN_FOCUSED).put(key, name);
    getActionMap().put(name, action);
}
 
Example 45
Project: incubator-netbeans   File: LibrariesNode.java   Source Code and License 5 votes vote down vote up
@NonNull
@Override
public Action createContextAwareInstance(Lookup actionContext) {
    final ClassPath scp = actionContext.lookup(ClassPath.class);
    final Supplier<FileObject[]> ctx = scp != null ?
            scp::getRoots :
            sources;
    return new AddLibraryAction(refHelper, ctx, filter);
}
 
Example 46
Project: incubator-netbeans   File: MacroRecording.java   Source Code and License 5 votes vote down vote up
/**
 * Record given action into a macro buffer.
 *
 * @param action non-null action to record
 * @param evt non-null evt used when recording typed text of default key-typed action.
 */
public synchronized void recordAction(Action action, ActionEvent evt, JTextComponent target) {
    if (!(isRecording() && !Boolean.TRUE.equals(action.getValue(NO_MACRO_RECORDING_PROPERTY)))) {
        return;
    }
    String actionName = actionName(action);
    if(action == target.getKeymap().getDefaultAction() ) { // defaultKeyTyped
        // see #218258; must filter key-typed events after key-pressed. Not ideal,
        // but shares logic with the actual action that inserts content into the editor.
        if (isValidDefaultTypedAction(evt) &&
            isValidDefaultTypedCommand(evt)) {
            textBuffer.append( evt.getActionCommand() );
        }
    } else {
        if (textBuffer.length() > 0) {
            if (macroBuffer.length() > 0) {
                macroBuffer.append( ' ' );
            }
            appendEncodedText(macroBuffer, textBuffer);
            textBuffer.setLength(0);
        }
        if (macroBuffer.length() > 0) {
            macroBuffer.append(' ');
        }
        // Append encoded action name
        for (int i = 0; i < actionName.length(); i++) {
            char c = actionName.charAt(i);
            if (Character.isWhitespace(c) || c == '\\') {
                macroBuffer.append('\\');
            }
            macroBuffer.append(c);
        }
    }
}
 
Example 47
Project: gate-core   File: MainFrame.java   Source Code and License 5 votes vote down vote up
protected void removeMenuItem(JMenuItem itemToRemove) {
  Action a = itemToRemove.getAction();
  // start by searching this menu
  XJMenu menuToUse = this;
  int firstIndex = firstPluginItem;
  // keep track of the parent menu
  XJMenu parentMenu = null;
  // if the action has a menu path set, navigate the path to find the
  // right menu.
  String[] menuPath = (String[])a.getValue(GateConstants.MENU_PATH_KEY);
  if(menuPath != null) {
    PATH_ELEMENT: for(String pathElement : menuPath) {
      int i;
      for(i = firstIndex; i < menuToUse.getItemCount(); i++) {
        JMenuItem item = menuToUse.getItem(i);
        if(item instanceof XJMenu && item.getText().equals(pathElement)) {
          // found the menu for this path element, move on to the next one
          firstIndex = 0;
          parentMenu = menuToUse;
          menuToUse = (XJMenu)item;
          continue PATH_ELEMENT;
        }
      }
      // we've reached the end of a menu without finding the sub-menu
      // we were looking for.  This shouldn't happen, but if it does then
      // we can ignore it as if there's no menu to remove the thing from
      // then there's nothing to remove either.
      return;
    }
  }

  // we have a menu to remove the item from: remove it
  menuToUse.remove(itemToRemove);
  if(menuToUse.getItemCount() == 0 && parentMenu != null) {
    // sub-menu is empty, remove it from parent
    parentMenu.remove(menuToUse);
  }
}
 
Example 48
Project: Dahlem_SER316   File: HTMLEditor.java   Source Code and License 5 votes vote down vote up
public RedoAction() {
	super(Local.getString("Redo"));
	setEnabled(false);
	putValue(
		Action.SMALL_ICON,
		new ImageIcon(cl.getResource("resources/icons/redo16.png")));
	putValue(
		Action.ACCELERATOR_KEY,
		KeyStroke.getKeyStroke(
			KeyEvent.VK_Z,
			KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK));
}
 
Example 49
Project: incubator-netbeans   File: PackageRootNode.java   Source Code and License 5 votes vote down vote up
@Override
@NonNull
public Action[] getActions(boolean context) {
    Action[] res = actions.get();
    if (res == null) {
        res = PackageView.createRootNodeActions();
        if(!actions.compareAndSet(null, res)) {
            res = actions.get();
        }
    }
    assert res != null;
    return res;
}
 
Example 50
Project: incubator-netbeans   File: EditorActionUtilities.java   Source Code and License 5 votes vote down vote up
public static Lookup.Result<Action> createActionsLookupResult(String mimeType) {
    if (!MimePath.validate(mimeType)) {
        throw new IllegalArgumentException("├Ćnvalid mimeType=\"" + mimeType + "\"");
    }
    Lookup lookup = Lookups.forPath(getPath(mimeType, "Actions"));
    return lookup.lookupResult(Action.class);
}
 
Example 51
Project: incubator-netbeans   File: ToggleFullScreenAction.java   Source Code and License 5 votes vote down vote up
public ToggleFullScreenAction() {
    addPropertyChangeListener( new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if( Action.ACCELERATOR_KEY.equals(evt.getPropertyName()) ) {
                synchronized( ToggleFullScreenAction.this ) {
                    //119127 - make sure shortcut gets updated in the menu
                    menuItems = null;
                    createItems();
                }
            }
        }
    });
}
 
Example 52
Project: incubator-netbeans   File: VersionNode.java   Source Code and License 5 votes vote down vote up
@Override
public Action[] getActions(boolean context) {
    Artifact artifact = RepositoryUtil.createArtifact(record);
    List<Action> actions = new ArrayList<Action>();
    actions.add(new ShowArtifactAction(record));
    actions.add(new AddAsDependencyAction(artifact));
    actions.add(CommonArtifactActions.createFindUsages(artifact));
    actions.add(CommonArtifactActions.createViewJavadocAction(artifact));
    actions.add(OpenAction.get(OpenAction.class));
    actions.add(new DownloadAction(artifact));
    actions.add(new DownloadAction(artifact, false));
    actions.add(new DownloadAction(artifact, true));
    actions.add(CopyAction.get(CopyAction.class));
    return actions.toArray(new Action[actions.size()]);
}
 
Example 53
Project: incubator-netbeans   File: UndockModeAction.java   Source Code and License 5 votes vote down vote up
/** Overriden to share accelerator between instances of this action.
 */ 
@Override
public Object getValue(String key) {
    if (Action.ACCELERATOR_KEY.equals(key)) {
        return ActionUtils.getSharedAccelerator("UndockModeAction"); //NOI18N
    } else {
        return super.getValue(key);
    }
}
 
Example 54
Project: rapidminer   File: FancyDropDownButton.java   Source Code and License 4 votes vote down vote up
public void add(Action action) {
	getPopupMenu().add(action);
}
 
Example 55
Project: incubator-netbeans   File: PinWatchValueProvider.java   Source Code and License 4 votes vote down vote up
public PinWatchValueProvider(ContextProvider lookupProvider) {
    this.lookupProvider = lookupProvider;
    debugger = (JPDADebuggerImpl) lookupProvider.lookupFirst(null, JPDADebugger.class);
    debugger.addPropertyChangeListener(JPDADebugger.PROP_CURRENT_CALL_STACK_FRAME, this);
    headAction = lookupProvider.lookupFirst("PinWatchHeadActions", Action.class);
}
 
Example 56
Project: VASSAL-src   File: ExtensionTree.java   Source Code and License 4 votes vote down vote up
protected Action buildAddAction(final Configurable target, final Class<? extends Buildable> newConfig) {
  return new AbstractAction("Add " + getConfigureName(newConfig)) {
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent evt) {
      Configurable ch = null;
      try {
        ch = (Configurable) newConfig.getConstructor().newInstance();
      }
      catch (Throwable t) {
        ReflectionUtils.handleNewInstanceFailure(t, newConfig);
      }

      if (ch != null) {
        final Configurable child = ch;

        child.build(null);
        if (child instanceof PieceSlot) {
          ((PieceSlot) child).updateGpId(extension);
        }
        if (child.getConfigurer() != null) {
          if (insert(target, child, getTreeNode(target).getChildCount())) {
            PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ExtensionTree.this), false, child, helpWindow) {
              private static final long serialVersionUID = 1L;

              public void save() {
                super.save();
                if (!isEditable(target)) {
                  ExtensionElement el = new ExtensionElement(child, getPath(getTreeNode(target)));
                  extension.add(el);
                }
              }

              public void cancel() {
                ExtensionTree.this.remove(target, child);
                dispose();
              }
            };
            w.setVisible(true);
          }
        }
        else {
          boolean inserted = insert(target, child, getTreeNode(target).getChildCount());
          if (inserted && !isEditable(getTreeNode(target))) {
            extension.add(new ExtensionElement(child, getPath(getTreeNode(target))));
          }
        }
      }
    }
  };
}
 
Example 57
Project: incubator-netbeans   File: BridgingIOProvider.java   Source Code and License 4 votes vote down vote up
@Override
public InputOutput getIO(String name, Action[] actions) {
    return new BridgingInputOutput(
            providerDelegate.getIO(name, true,
                    Lookups.fixed((Object[]) actions)));
}
 
Example 58
Project: pdfjumbler   File: PdfJumbler.java   Source Code and License 4 votes vote down vote up
public ZoomInAction(PdfJumbler parent) {
	super(resources.getString("ZOOM_IN"), Icons.ZOOM_IN);
	this.parent = parent;
	putValue(Action.SHORT_DESCRIPTION, resources.getString("ZOOM_IN"));
	putValue(Action.ACCELERATOR_KEY, resources.getObject("ACCELERATOR:ZOOM_IN"));
}
 
Example 59
Project: Pogamut3   File: ExpandedActionPresenter.java   Source Code and License 4 votes vote down vote up
@Override
public Action[] getMenuActions() {
    return null;
}
 
Example 60
Project: incubator-netbeans   File: Actions.java   Source Code and License 4 votes vote down vote up
@Override public Action fileCommandAction(String command, String name, Icon icon) {
    return new FileAction( command, name, icon, null );
}