下面列出了怎么用javax.swing.AbstractAction的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Registers a keyboard handler to a given component
*
* @param component Component to register the handler to
* @param condition see {@link JComponent} and {@link JComponent#WHEN_IN_FOCUSED_WINDOW}
* @param stroke Keystroke to activate the handler
* @param listener ActionListener to handle the key press
* @param actionCommand Action command string
*/
public static void registerKeyHandler(JComponent component, int condition, KeyStroke stroke,
final ActionListener listener, final String actionCommand) {
component.getInputMap(condition).put(stroke, actionCommand);
component.getActionMap().put(actionCommand, new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
ActionEvent newEvent =
new ActionEvent(event.getSource(), ActionEvent.ACTION_PERFORMED, actionCommand);
listener.actionPerformed(newEvent);
}
});
}
private static JButton createFontStyleBoldButton(DrawingEditor editor) {
JButton button = new JButton();
button.setIcon(ImageDirectory.getImageIcon("/toolbar/attributeFontBold.png"));
button.setText(null);
button.setToolTipText(BUNDLE.getString("buttonFactory.button_fontStyleBold.tooltipText"));
button.setFocusable(false);
AbstractAction action
= new AttributeToggler<>(editor,
AttributeKeys.FONT_BOLD,
Boolean.TRUE,
Boolean.FALSE,
new StyledEditorKit.BoldAction());
action.putValue(ActionUtil.UNDO_PRESENTATION_NAME_KEY,
BUNDLE.getString("buttonFactory.action_fontStyleBold.undo.presentationName"));
button.addActionListener(action);
return button;
}
/**
* @param text
* this is an optional action name. If this is null a default
* name like "New Document" is used, but you can customize this
* to resemble "New Spreadsheet" or "New Image".
*/
public NewDocumentAction(DocumentControls controls, String text) {
Objects.requireNonNull(controls);
this.controls = controls;
DocumentCommand.NEW.install(this);
controls.registerAction(this);
if (text != null)
putValue(AbstractAction.NAME, text);
controls.getOpenDocuments().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
refresh();
}
}, false);
refresh();
}
public Action getDisableSpatialIndexAction( ColumnLevel column, DatabaseViewer spatialiteViewer ) {
if (sqlTemplates.hasRecoverSpatialIndex()) {
return new AbstractAction("Disable spatial index"){
@Override
public void actionPerformed( ActionEvent e ) {
String tableName = column.parent.tableName;
String columnName = column.columnName;
String query = sqlTemplates.disableSpatialIndex(tableName, columnName);
spatialiteViewer.addTextToQueryEditor(query);
}
};
} else {
return null;
}
}
public void installKeyboardActions(JComponent c) {
c.getInputMap().put(DELETE_KEYSTROKE, VK_DELETE_KEY);
c.getActionMap().put(VK_DELETE_KEY, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
BoundedTableModel dataModel = bar.getDataModel();
ListSelectionModel selectionModel = bar.getSelectionModel();
MarkerMutationModel mutationModel = bar.getMutationModel();
if (selectionModel != null && dataModel != null
&& mutationModel != null
&& !selectionModel.isSelectionEmpty()) {
int selected = selectionModel.getLeadSelectionIndex();
if (dataModel.isCellEditable(selected, bar
.getPositionColumn())) {
mutationModel.removeMarkerAtIndex(selected);
}
}
}
});
}
protected PumpCommand(String text, Character accelerator,
String commandName, Class<T> actionClass) {
if (text != null) {
properties.put(AbstractAction.NAME, text);
}
if (accelerator != null) {
int modifiers = Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask();
KeyStroke keyStroke = KeyStroke.getKeyStroke(
accelerator.charValue(), modifiers);
properties.put(AbstractAction.ACCELERATOR_KEY, keyStroke);
}
if (commandName != null) {
properties.put(AbstractAction.ACTION_COMMAND_KEY, commandName);
}
this.actionClass = actionClass;
}
private Action selectNextRowAction() {
return new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ProfilerColumnModel cModel = table._getColumnModel();
if (table.getRowCount() == 0 || cModel.getVisibleColumnCount() == 0) return;
int row = table.getSelectedRow();
if (row == -1) {
table.selectColumn(cModel.getFirstVisibleColumn(), false);
table.selectRow(0, true);
} else {
if (++row == table.getRowCount()) {
row = 0;
int column = table.getSelectedColumn();
if (column == -1) column = cModel.getFirstVisibleColumn();
column = cModel.getNextVisibleColumn(column);
table.selectColumn(column, false);
}
table.selectRow(row, true);
}
}
};
}
@Override
public void registerFocusHotkey( final JComponent rootComponent, final KeyStroke keyStroke ) {
final Object actionKey = new Object();
final String toolTipText = getToolTipText();
if ( toolTipText != null ) {
if ( toolTipText.endsWith( "</html>" ) )
setToolTipText( toolTipText.substring( 0, toolTipText.length() - 7 ) + LGuiUtils.keyStrokeToString( keyStroke ) + "</html>" );
else
setToolTipText( toolTipText + LGuiUtils.keyStrokeToString( keyStroke ) );
}
rootComponent.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ).put( keyStroke, actionKey );
rootComponent.getActionMap().put( actionKey, new AbstractAction() {
@Override
public void actionPerformed( final ActionEvent event ) {
requestFocusInWindow();
}
} );
}
/**
* Shows the popup immediately below the specified field. If item is selected,
* sets the field text and fires property change.
*
* @param field the field that displays the selected string
*/
public void showPopup(final JTextField display) {
//display = field;
Action selectAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
int prev = selected;
selected = Integer.parseInt(e.getActionCommand());
display.setText(items[selected]);
OSPCombo.this.firePropertyChange("index", prev, -1); //$NON-NLS-1$
}
};
removeAll();
for(int i = 0; i<items.length; i++) {
String next = items[i].toString();
JMenuItem item = new JMenuItem(next);
item.setFont(display.getFont());
item.addActionListener(selectAction);
item.setActionCommand(String.valueOf(i));
add(item);
}
int popupHeight = 8+getComponentCount()*display.getHeight();
setPopupSize(display.getWidth(), popupHeight);
show(display, 0, display.getHeight());
}
ClosableTab(String name, TabCloseCallBack closeCallBack) {
setName(name);
setLayout(null);
closeTabButton = new JButton("Close");
closeTabButton.setLocation(720, 5);
closeTabButton.setSize(new Dimension(70, 30));
closeTabButton.setFont(closeTabButton.getFont().deriveFont(10.0f));
add(closeTabButton);
closeTabButton.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
closeCallBack.call(name);
}
});
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
if (!ProfilingPointsManager.getDefault().isProfilingSessionInProgress()) {
Collection<? extends CodeProfilingPoint.Annotation> anns = actionContext.lookupAll(CodeProfilingPoint.Annotation.class);
if (anns.size() == 1) {
final CodeProfilingPoint pp = anns.iterator().next().profilingPoint();
return new AbstractAction(getName()) {
@Override
public void actionPerformed(ActionEvent ae) {
ProfilingPointsManager.getDefault().removeProfilingPoint(pp);
}
};
}
}
return this;
}
private ActionDescriptor createExportToIDL() {
ActionDescriptor descriptor = new ActionDescriptor();
descriptor.setMenu("IDEF0");
AbstractAction action = new AbstractAction() {
{
putValue(ACTION_COMMAND_KEY, "ExportToIDL");
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
exportToIdl();
}
};
descriptor.setAction(action);
return descriptor;
}
private static void exchangeCommands(String[][] commandsToExchange,
final JComponent target, final JComponent source) {
InputMap targetBindings = target.getInputMap();
KeyStroke[] targetBindingKeys = targetBindings.allKeys();
ActionMap targetActions = target.getActionMap();
InputMap sourceBindings = source.getInputMap();
ActionMap sourceActions = source.getActionMap();
for (int i = 0; i < commandsToExchange.length; i++) {
String commandFrom = commandsToExchange[i][0];
String commandTo = commandsToExchange[i][1];
final Action orig = targetActions.get(commandTo);
if (orig == null) {
continue;
}
sourceActions.put(commandTo, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
orig.actionPerformed(new ActionEvent(target, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers()));
}
});
for (int j = 0; j < targetBindingKeys.length; j++) {
if (targetBindings.get(targetBindingKeys[j]).equals(commandFrom)) {
sourceBindings.put(targetBindingKeys[j], commandTo);
}
}
}
}
/**
* Manage low level key strokes ESCAPE : Close the window
*
* @return
*/
protected JRootPane createRootPane() {
JRootPane rootPane = new JRootPane();
KeyStroke strokeEscape = KeyStroke.getKeyStroke("ESCAPE");
@SuppressWarnings("serial")
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
setVisible(false);
}
};
InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(strokeEscape, "ESCAPE");
rootPane.getActionMap().put("ESCAPE", actionListener);
return rootPane;
}
FindInQueryBar(FindInQuerySupport support) {
this.support = support;
initComponents();
lastSearchModel = new DefaultComboBoxModel();
findCombo.setModel(lastSearchModel);
findCombo.setSelectedItem(""); // NOI18N
initialized = true;
addComboEditorListener();
InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
String closeKey = "close"; // NOI18N
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), closeKey);
getActionMap().put(closeKey, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
FindInQueryBar.this.support.cancel();
}
});
}
/** Registers shortcut for enable/ disable auto-hide functionality */
@Override
public void registerShortcuts(JComponent comp) {
comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE,
InputEvent.CTRL_DOWN_MASK), PIN_ACTION);
comp.getActionMap().put(PIN_ACTION, pinAction);
//TODO make shortcut configurable
comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0,
InputEvent.CTRL_DOWN_MASK), TRANSPARENCY_ACTION);
comp.getActionMap().put(TRANSPARENCY_ACTION, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
shouldPerformAction(TabbedContainer.COMMAND_TOGGLE_TRANSPARENCY, getSelectionModel().getSelectedIndex(), null);
}
});
}
private void addTool(final Tool t, JMenu menu, JToolBar toolbar, ButtonGroup menuGroup, ButtonGroup toolbarGroup) {
final JToggleButton toggle = new JToggleButton();
final JCheckBoxMenuItem check = new JCheckBoxMenuItem();
Action action = new AbstractAction(t.getName()) {
@Override
public void actionPerformed(ActionEvent e) {
if (currentTool != null) {
currentTool.deactivate();
}
currentTool = t;
toggle.setSelected(true);
check.setSelected(true);
currentTool.activate();
}
};
toggle.setAction(action);
check.setAction(action);
menu.add(check);
toolbar.add(toggle);
menuGroup.add(check);
toolbarGroup.add(toggle);
}
/**
* Converts a given column to buttons. The existing column data text will become the text of the
* new buttons.
*
* @param table The table to be updated.
* @param column Zero-based column number of the table.
* @param buttonListener The listener that will be fired when one of the new buttons are clicked.
*/
public static void attachButtonColumn(
final JTable table,
final int column,
final BiConsumer<Integer, DefaultTableModel> buttonListener) {
Preconditions.checkState(table.getModel().getColumnCount() > column);
new ButtonColumn(
table,
column,
new AbstractAction() {
private static final long serialVersionUID = 786926815237533866L;
@Override
public void actionPerformed(final ActionEvent e) {
final int rowNumber = Integer.parseInt(e.getActionCommand());
final DefaultTableModel defaultTableModel = (DefaultTableModel) table.getModel();
buttonListener.accept(rowNumber, defaultTableModel);
}
});
}
public @Override Action createContextAwareInstance(final Lookup context) {
return new AbstractAction(BTN_Open_Project()) {
public @Override void actionPerformed(ActionEvent e) {
Set<Project> projects = new HashSet<Project>();
for (Artifact art : context.lookupAll(Artifact.class)) {
File f = art.getFile();
if (f != null) {
Project p = FileOwnerQuery.getOwner(org.openide.util.Utilities.toURI(f));
if (p != null) {
projects.add(p);
}
}
}
OpenProjects.getDefault().open(projects.toArray(new NbMavenProjectImpl[projects.size()]), false, true);
}
};
}
/**
* Workaround for a swing bug : when the user enters an illegal value, the
* text is forced to the last value.
*
* @param spinner the spinner to update
*/
public static void fixIntegerList (final JSpinner spinner)
{
JSpinner.DefaultEditor editor;
editor = (JSpinner.DefaultEditor) spinner.getEditor();
final JFormattedTextField ftf = editor.getTextField();
ftf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterAction");
ftf.getActionMap().put("enterAction", new AbstractAction()
{
@Override
public void actionPerformed (ActionEvent e)
{
try {
spinner.setValue(Integer.parseInt(ftf.getText()));
} catch (NumberFormatException ex) {
// Reset to last value
ftf.setText(ftf.getValue().toString());
}
}
});
}
private Action onRenameAction() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
assignThePreviouslySelected();
Boolean flag = testDesign.getProject().getTestData()
.renameTestDataColumn(std.getName(),
getValue("oldvalue").toString(),
getValue("newvalue").toString());
putValue("rename", flag);
if (flag) {
selectThePreviouslySelected();
}
}
};
}
public Action getCheckSpatialIndexAction( ColumnLevel column, DatabaseViewer spatialiteViewer ) {
if (sqlTemplates.hasRecoverSpatialIndex()) {
return new AbstractAction("Check spatial index"){
@Override
public void actionPerformed( ActionEvent e ) {
String tableName = column.parent.tableName;
String columnName = column.columnName;
String query = sqlTemplates.checkSpatialIndex(tableName, columnName);
spatialiteViewer.addTextToQueryEditor(query);
}
};
} else {
return null;
}
}
private AbstractAction getSelectColorAction() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
final Color newColor = JColorChooser.showDialog(null, MText.get(_S1), getBackground());
if (newColor != null) {
setBackground(newColor);
}
}
};
}
/**
* Small helper function for adding buttons to the toolbar.
*
* @param toolBar
* @param action Action associated with the new button.
* @param defaultIconPath Path to the default icon for the button.
* @param rolloverIconPath Path to the roll-over icon for the button.
* @param pressedIconPath Path to the pressed icon for the button.
*
* @return The created button.
*/
// ESCA-JAVA0138:
private static JButton createAndAddIconToToolbar(final JToolBar toolBar,
final AbstractAction action, final String defaultIconPath, final String rolloverIconPath,
final String pressedIconPath) {
final JButton button = toolBar.add(CActionProxy.proxy(action));
button.setBorder(new EmptyBorder(0, 0, 0, 0));
button.setIcon(new ImageIcon(CMain.class.getResource(defaultIconPath)));
button.setRolloverIcon(new ImageIcon(CMain.class.getResource(rolloverIconPath)));
button.setPressedIcon(new ImageIcon(CMain.class.getResource(pressedIconPath)));
return button;
}
public Action createGotoAction(final Figure f) {
final DiagramScene diagramScene = this;
Action a = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
diagramScene.gotoFigure(f);
}
};
a.setEnabled(true);
a.putValue(Action.SMALL_ICON, new ColorIcon(f.getColor()));
String name = f.getLines()[0];
name += " (";
if (f.getCluster() != null) {
name += "B" + f.getCluster().toString();
}
if (!this.getFigureWidget(f).isVisible()) {
if (f.getCluster() != null) {
name += ", ";
}
name += "hidden";
}
name += ")";
a.putValue(Action.NAME, name);
return a;
}
/**
*
*/
public BufrTableBPanel(PreferencesExt p) {
super(p, "tableB:", false, false);
AbstractAction fileAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
FileManager bufrFileChooser = ToolsUI.getBufrFileChooser();
String filename = bufrFileChooser.chooseFilename();
if (filename == null) {
return;
}
cb.setSelectedItem(filename);
}
};
BAMutil.setActionProperties(fileAction, "FileChooser", "open Local table...", false, 'L', -1);
BAMutil.addActionToContainer(buttPanel, fileAction);
modes = new JComboBox<>(BufrTables.Format.values());
buttPanel.add(modes);
JButton acceptButton = new JButton("Accept");
buttPanel.add(acceptButton);
acceptButton.addActionListener(e -> accept());
tables = new JComboBox<>(BufrTables.getTableConfigsAsArray());
buttPanel.add(tables);
tables.addActionListener(e -> acceptTable((BufrTables.TableConfig) tables.getSelectedItem()));
bufrTable = new BufrTableBViewer(prefs, buttPanel);
add(bufrTable, BorderLayout.CENTER);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private AbstractAction generateActionFromKey(MTGKeyWord k) throws NoSuchMethodException,InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
Class a = PluginRegistry.inst().loadClass("org.magic.game.actions.cards." + k.toString() + "Actions");
Constructor ctor = a.getDeclaredConstructor(DisplayableCard.class);
AbstractAction aaction = (AbstractAction) ctor.newInstance(this);
aaction.putValue(Action.LONG_DESCRIPTION, k.getKeyword());
return aaction;
}
public Action getAction(final T value) {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
set(value);
}
};
}
public static void setKeyEvent(JComponent widget, int keyEvent, Runnable action) {
String inputMapKey = "key_" + keyEvent;
widget.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(keyEvent, 0),
inputMapKey
);
widget.getActionMap().put(inputMapKey, new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
action.run();
}
});
}
@Override
protected AbstractAction getCancelAction() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
doCancelAndClose();
}
};
}