下面列出了java.awt.event.HierarchyBoundsListener#javax.swing.Action 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testAddRemoveAction() throws Exception {
AbstractAction realAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
FileObject actionFile = SnapUtils.addAction(realAction, "Test/Action");
assertNotNull(actionFile);
assertNotNull(actionFile.getParent());
assertEquals("application/x-nbsettings", actionFile.getMIMEType());
assertEquals("Test/Action", actionFile.getParent().getPath());
assertEquals("instance", actionFile.getExt());
Action action = FileUtil.getConfigObject(actionFile.getPath(), Action.class);
assertNotNull(action);
assertEquals(TransientAction.class, action.getClass());
assertSame(realAction, ((TransientAction) action).getDelegate());
boolean ok = SnapUtils.removeAction(actionFile);
assertEquals(true, ok);
action = FileUtil.getConfigObject(actionFile.getPath(), Action.class);
assertNull(action);
}
/** Implements superclass abstract method. Creates nodes from key.
* @return <code>PendingActionNode</code> if key is of
* <code>Action</code> type otherwise <code>null</code> */
protected Node[] createNodes(Object key) {
Node n = null;
if(key instanceof Action) {
Action action = (Action)key;
Icon icon = (action instanceof SystemAction) ?
((SystemAction)action).getIcon() : null;
String actionName = (String)action.getValue(Action.NAME);
if (actionName == null) actionName = ""; // NOI18N
actionName = org.openide.awt.Actions.cutAmpersand(actionName);
n = new NoActionNode(icon, actionName, NbBundle.getMessage(
Install.class, "CTL_ActionInProgress", actionName));
} else if (key instanceof ExecutorTask) {
n = new NoActionNode(null, key.toString(),
NbBundle.getMessage(Install.class, "CTL_PendingExternalProcess2",
// getExecutionEngine() had better be non-null, since getPendingTasks gave an ExecutorTask:
ExecutionEngine.getExecutionEngine().getRunningTaskName((ExecutorTask) key))
);
} else if (key instanceof InternalHandle) {
n = new NoActionNode(null, ((InternalHandle)key).getDisplayName(), null);
}
return n == null ? null : new Node[] { n };
}
private JMenu createDataStrokeWidthMenu() {
JMenu menu = new JMenu("Data stroke width");
ButtonGroup group = new ButtonGroup();
for (final int width : new int[]{1, 2, 3}) {
Action setStrokeWidth = new AbstractAction(width + " px") {
@Override
public void actionPerformed(ActionEvent event) {
graphPane.setDataStrokeWidth(width);
}
};
AbstractButton button = new JCheckBoxMenuItem(setStrokeWidth);
if (width == 1) {
button.doClick();
}
group.add(button);
menu.add(button);
}
return menu;
}
public Action getOpenInSldEditorAction( TableLevel table, DatabaseViewer spatialiteViewer ) {
if (spatialiteViewer.currentConnectedDatabase.getType() == EDb.GEOPACKAGE) {
return new AbstractAction("Open in SLD editor"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
DefaultGuiBridgeImpl gBridge = new DefaultGuiBridgeImpl();
String databasePath = spatialiteViewer.currentConnectedDatabase.getDatabasePath();
final MainController controller = new MainController(new File(databasePath), table.tableName);
final JFrame frame = gBridge.showWindow(controller.asJComponent(), "HortonMachine SLD Editor");
Class<DatabaseViewer> class1 = DatabaseViewer.class;
ImageIcon icon = new ImageIcon(class1.getResource("/org/hortonmachine/images/hm150.png"));
frame.setIconImage(icon.getImage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
} else {
return null;
}
}
@SuppressWarnings("unchecked")
private void addTreeItem(String menu, Action action, ViewPlugin plugin) {
String[] strings = menu.split("/");
for (int i = 0; i < strings.length; i++) {
strings[i] = plugin.getString("Menu." + strings[i]);
}
TreeList map = mainMenu;
for (int i = 0; i < strings.length - 1; i++) {
TreeList m = (TreeList) map.get(strings[i]);
if (m == null) {
m = new TreeList();
map.put(strings[i], m);
}
map = m;
}
ArrayList<Action> actions = (ArrayList<Action>) map
.get(strings[strings.length - 1]);
if (actions == null) {
actions = new ArrayList<Action>();
map.put(strings[strings.length - 1], actions);
}
actions.add(action);
}
public Action[] getActions(VCSContext ctx, VCSAnnotator.ActionDestination destination) {
Lookup context = ctx.getElements();
List<Action> actions = new ArrayList<Action>();
if (destination == VCSAnnotator.ActionDestination.MainMenu) {
actions.add(SystemAction.get(ShowHistoryAction.class));
actions.add(SystemAction.get(RevertDeletedAction.class));
} else {
actions.add(SystemActionBridge.createAction(
SystemAction.get(ShowHistoryAction.class),
NbBundle.getMessage(ShowHistoryAction.class, "CTL_ShowHistory"),
context));
actions.add(SystemActionBridge.createAction(
SystemAction.get(RevertDeletedAction.class),
NbBundle.getMessage(RevertDeletedAction.class, "CTL_ShowRevertDeleted"),
context));
}
return actions.toArray(new Action[actions.size()]);
}
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;
}
@Test
public void testWrapperAction() {
Map attrs = new HashMap(SIMPLE_ATTRS);
attrs.put(AbstractEditorAction.WRAPPER_ACTION_KEY, true);
final MyAction a = new MyAction(); // No attrs passed
attrs.put("delegate", a);
WrapperEditorAction wrapperAction = WrapperEditorAction.create(attrs);
JTextComponent c = new JEditorPane();
assertEquals("my-name", wrapperAction.getValue(Action.NAME));
assertNull(a.getValue(Action.NAME));
ActionEvent evt = new ActionEvent(c, 0, "");
wrapperAction.actionPerformed(evt);
assertEquals(Thread.currentThread(), a.actionPerformedThread);
// Properties transferred
assertEquals("my-name", a.getValue(Action.NAME));
}
private Action getPlayerAction(
final String title,
final Supplier<RetreatResult> showDialog,
final CompletableFuture<Territory> future) {
return SwingAction.of(
title,
e -> {
actionButton.setEnabled(false);
final RetreatResult retreatResult = showDialog.get();
if (retreatResult.isConfirmed()) {
future.complete(retreatResult.getTarget());
actionButton.setAction(nullAction);
}
actionButton.setEnabled(true);
});
}
/**
* Creates a Copy Button
*
* @param text
* Text to copy into clipboard
* @return
*/
private static JButton makeCopyButton(String text) {
Action copyAction = new ResourceAction(true, "browser_unavailable.copy") {
private static final long serialVersionUID = 1L;
@Override
public void loggedActionPerformed(ActionEvent e) {
StringSelection stringSelection = new StringSelection(text);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
};
JButton copyButton = new JButton(copyAction);
return copyButton;
}
public JToolBar createToolBar() {
JToolBar bar = new JToolBar();
for (Action action : getActions()) {
if (action != null) {
String command = (String) action
.getValue(Action.ACTION_COMMAND_KEY);
JButton button = bar.add(action);
button.setFocusable(false);
if (action.getValue(Action.SHORT_DESCRIPTION) == null) {
String text = null;
StringGetter getter = (StringGetter) action
.getValue(StringGetter.ACTION_STRING_GETTER);
if (getter != null)
text = getter.getString(command);
else
text = GlobalResourcesManager.getString(command);
if (text != null)
button.setToolTipText(text);
}
} else
bar.addSeparator();
}
return bar;
}
/**
* Create the theme's audio submenu.
*
* @param menu the menu
* @param label the label
* @param mnemonic the mnemonic
* @param accessibleDescription the accessible description
* @param action the action
* @return the j menu item
*/
public JMenuItem createAudioMenuItem(JMenu menu, String label,
String mnemonic,
String accessibleDescription,
Action action) {
JRadioButtonMenuItem mi = (JRadioButtonMenuItem) menu.add(new JRadioButtonMenuItem(getString(label)));
audioMenuGroup.add(mi);
mi.setMnemonic(getMnemonic(mnemonic));
mi.getAccessibleContext().setAccessibleDescription(getString(accessibleDescription));
mi.addActionListener(action);
return mi;
}
public EditorAction(String nameKey, String iconKey, String toolTipKey, Options options) {
super(options.getMsg(nameKey), ResourceManager.getImageIcon(iconKey));
this.options = options;
if (toolTipKey != null)
putValue(AbstractAction.SHORT_DESCRIPTION, options.getMsg(toolTipKey));
String s = options.getMessages().get(nameKey + "_keys");
if (s != null && s.length() >= 2 && !s.startsWith(nameKey)) {
putValue(Action.MNEMONIC_KEY, new Integer(s.charAt(0)));
if (s.charAt(1) != '*') {
char ch = s.charAt(1);
int key = (int) ch;
int keyMod = KeyEvent.CTRL_MASK;
if (ch == '#' && s.length() > 2) {
try {
int sep = s.indexOf('#', 2);
String k;
if (sep > 0) {
keyMod = Integer.parseInt(s.substring(sep + 1));
k = s.substring(2, sep);
} else {
k = s.substring(2);
}
key = Integer.parseInt(k);
} catch (Exception ex) {
System.err.println("Error initializing action keys\nBad expression: " + s);
}
}
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(key, keyMod));
}
}
setEnabled(false);
}
/**
* Creates the preview file chooser button.
*
* @return the j button
*/
public JButton createPreviewFileChooserButton() {
Action a = new AbstractAction(getString("FileChooserDemo.previewbutton")) {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = createFileChooser();
// Add filefilter & fileview
javax.swing.filechooser.FileFilter filter = createFileFilter(
getString("FileChooserDemo.filterdescription"),
"jpg", "gif");
ExampleFileView fileView = new ExampleFileView();
fileView.putIcon("jpg", jpgIcon);
fileView.putIcon("gif", gifIcon);
fc.setFileView(fileView);
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
// add preview accessory
fc.setAccessory(new FilePreviewer(fc));
// show the filechooser
int result = fc.showOpenDialog(getDemoPanel());
// if we selected an image, load the image
if(result == JFileChooser.APPROVE_OPTION) {
loadImage(fc.getSelectedFile().getPath());
}
}
};
return createButton(a);
}
/**
* Creates an action that opens Watches TopComponent.
*/
public static Action createWatchesViewAction() {
ViewActions action = new ViewActions("watchesView");
// When changed, update also mf-layer.xml, where are the properties duplicated because of Actions.alwaysEnabled()
action.putValue (Action.NAME, "CTL_WatchesAction");
action.putValue ("iconbase",
"org/netbeans/modules/debugger/resources/watchesView/watch_16.png" // NOI18N
);
return action;
}
public InspectAction() {
super(VALUE_NAME, ActionManager.getIcon(VALUE_SMALL_ICON));
putValue(Action.ACTION_COMMAND_KEY, VALUE_COMMAND);
putValue(Action.SHORT_DESCRIPTION, VALUE_SHORT_DESCRIPTION);
putValue(Action.LONG_DESCRIPTION, VALUE_LONG_DESCRIPTION);
putValue(Action.MNEMONIC_KEY, VALUE_MNEMONIC);
}
@Override
public Action getPreferredAction() {
Action[] actions = getActions(true);
for (Action action : actions) {
if (action instanceof GoToSourceAction) {
return action;
}
}
return null;
}
JPopupMenu createPopupMenu() {
// Get actions for the node
List<Action>[] actionsArray = getActions();
List<Action> defaultActions = actionsArray[0];
List<Action> actions = actionsArray[1];
// Return if there are no actions to display
if (defaultActions.size() == 0 && actions.size() == 0) return null;
// Create a popup menu
JPopupMenu popupMenu = new JPopupMenu();
// Insert default actions
boolean realDefaultAction = true;
if (!defaultActions.isEmpty()) {
for (Action defaultAction : defaultActions) {
JMenuItem defaultItem = new DataSourceItem(defaultAction);
if (realDefaultAction) {
defaultItem.setFont(defaultItem.getFont().deriveFont(Font.BOLD));
realDefaultAction = false;
}
popupMenu.add(defaultItem);
}
}
// Insert separator between default action and other actions
if (!defaultActions.isEmpty() && !actions.isEmpty()) popupMenu.addSeparator();
// Insert other actions
if (!actions.isEmpty()) {
for (Action action : actions) {
if (action == null) popupMenu.addSeparator();
else popupMenu.add(createItem(action));
}
}
return popupMenu;
}
/**
* Adds the new perspective action to the menu.
*/
private void addNewPerspectiveAction() {
Action newPerspectiveAction = new NewPerspectiveAction();
newPerspectiveAction.putValue(Action.LARGE_ICON_KEY, null);
newPerspectiveAction.putValue(Action.SMALL_ICON, null);
JMenuItem item = new JMenuItem(newPerspectiveAction);
item.setPreferredSize(new Dimension(item.getPreferredSize().width + 30, item.getPreferredSize().height));
popupMenu.addSeparator();
popupMenu.add(item);
popupMenu.addSeparator();
}
public javax.swing.Action[] getActions() {
Action[] actions = callback.createDefaultActions();
SystemAction fsAction = SystemAction.get(FileSystemAction.class);
if (!Arrays.asList(actions).contains(fsAction)) {
Action[] newActions = new Action[actions.length+1];
System.arraycopy(actions, 0, newActions, 0, actions.length);
newActions[actions.length] = fsAction;
actions = newActions;
}
return actions;
}
private void addKeyBindingsFor(Action action, char binding) {
String bindingValue = Character.toString(binding);
JRootPane rootPane = parentFrame.getRootPane();
rootPane.getInputMap().put(KeyStroke.getKeyStroke(bindingValue), action.getClass().getSimpleName());
rootPane.getActionMap().put(action.getClass().getSimpleName(), action);
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(bindingValue));
}
Action getCustomEditorAction() {
if (customEditorAction == null) {
customEditorAction = new CustomEditorAction(this);
}
return customEditorAction;
}
/**
* This test should test behaviour of the getActions method when
* there is some alien object specified in the configuration folder.
* The testing object is of type Integer (instead of javax.swing.Action).
*/
public void testWrongActionObjectInConfig() throws Exception {
assertEquals("No actions at the start", 0, node.getActions(false).length);
FileObject test = root;
FileObject a1 = test.createData("java-lang-String.instance");
Action [] res = node.getActions(false);
assertEquals("There should be zero actions.", 0, res.length);
}
private void addAction(JPopupMenu popup, Action action) {
if (action == null) {
popup.addSeparator();
} else {
Class cls = (Class)action.getValue(KEY_CLASS);
if (Boolean.class.equals(cls)) {
Boolean boolvalue = (Boolean)action.getValue(KEY_BOOLVALUE);
JCheckBoxMenuItem item = new JCheckBoxMenuItem(action);
item.setSelected(boolvalue);
popup.add(item);
} else {
popup.add(action);
}
}
}
public JavaStackTraceAction() {
super(VALUE_NAME, ActionManager.getIcon(VALUE_SMALL_ICON));
putValue(Action.ACTION_COMMAND_KEY, VALUE_COMMAND);
putValue(Action.SHORT_DESCRIPTION, VALUE_SHORT_DESCRIPTION);
putValue(Action.LONG_DESCRIPTION, VALUE_LONG_DESCRIPTION);
putValue(Action.MNEMONIC_KEY, VALUE_MNEMONIC);
}
public ClearSplitAction(TopComponent tc) {
// Replaced by weak ref since strong ref led to leaking of editor panes
this.tcRef = new WeakReference<TopComponent>(tc);
putValue(Action.NAME, Bundle.LBL_ClearSplitAction());
//hack to insert extra actions into JDev's popup menu
putValue("_nb_action_id_", Bundle.LBL_ValueClearSplit()); //NOI18N
if (tc instanceof Splitable) {
setEnabled(((Splitable) tc).getSplitOrientation() != -1);
} else {
setEnabled(false);
}
}
public ShowAction() {
super(VALUE_NAME, ActionManager.getIcon(VALUE_SMALL_ICON));
putValue(Action.ACTION_COMMAND_KEY, VALUE_COMMAND);
putValue(Action.SHORT_DESCRIPTION, VALUE_SHORT_DESCRIPTION);
putValue(Action.LONG_DESCRIPTION, VALUE_LONG_DESCRIPTION);
putValue(Action.MNEMONIC_KEY, VALUE_MNEMONIC);
}
public static DebuggerAction createStepOutAction () {
DebuggerAction action = new DebuggerAction(ActionsManager.ACTION_STEP_OUT);
action.putValue (Action.NAME, "CTL_Step_out_action_name");
action.putValue (
"iconBase", // NOI18N
"org/netbeans/modules/debugger/resources/actions/StepOut.gif" // NOI18N
);
return action;
}
public static void installEscapeCloseOperation(final JDialog dialog) {
@SuppressWarnings("serial")
Action dispatchClosing = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent event) {
dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
}
};
JRootPane root = dialog.getRootPane();
root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE_STROKE, DISPATCH_WINDOW_CLOSING_ACTION_MAP_KEY);
root.getActionMap().put(DISPATCH_WINDOW_CLOSING_ACTION_MAP_KEY, dispatchClosing);
}
@Override
public Action[] getActions(NodeActionsProvider original, Object node) throws UnknownTypeException {
Action[] actions = original.getActions(node);
int n = actions.length;
Action[] newActions = new Action[n+1];
System.arraycopy(actions, 0, newActions, 0, n);
if (switchViewAction == null) {
switchViewAction = getSwitchViewAction();
}
newActions[n] = switchViewAction;
return newActions;
}