下面列出了怎么用javax.swing.MenuElement的API类实例代码及写法,或者点击链接到github查看源代码。
public void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager) {
if (isReturnAction(e)) { // Handle SPACE and ENTER
MenuElement[] p = manager.getSelectedPath();
MenuElement m = p != null && p.length > 0 ? p[p.length - 1] : null;
if (m instanceof StayOpen) {
e.consume();
if (e.getID() == KeyEvent.KEY_PRESSED)
performAction((StayOpen)m, e.getModifiers());
return;
}
} else for (Component component : getComponents()) { // Handle mnemonics and accelerators
if (component instanceof StayOpen) {
StayOpen item = (StayOpen)component;
JMenuItem i = item.getItem();
KeyStroke k = KeyStroke.getKeyStrokeForEvent(e);
if (k.equals(mnemonic(i)) || k.equals(i.getAccelerator())) {
e.consume();
manager.setSelectedPath(new MenuElement[] { this, i });
performAction(item, e.getModifiers());
return;
}
}
}
super.processKeyEvent(e, path, manager);
}
@CalledOnlyBy(AmidstThread.EDT)
private void runOnMenuItems(MenuElement menuElement, String[] textRepresentations, Consumer<JMenuItem> consumer) {
MenuElement[] elements = menuElement.getSubElements();
if(elements != null) {
for(MenuElement element : elements) {
if(element instanceof JMenuItem) {
for(String s : textRepresentations) {
if(((JMenuItem) element).getText().equals(s)) {
consumer.accept((JMenuItem) element);
}
}
}
runOnMenuItems(element, textRepresentations, consumer);
}
}
}
/**
* Recursively attach the given action listener to all items in the
* given menu that have a non-<code>null</code> action command
*
* @param menuElement The menu element
* @param actionListener The action listener
*/
private static void attachActionListener(
MenuElement menuElement, ActionListener actionListener)
{
if (menuElement instanceof JMenuItem)
{
JMenuItem menuItem = (JMenuItem)menuElement;
if (menuItem.getActionCommand() != null)
{
menuItem.addActionListener(actionListener);
}
}
MenuElement[] subElements = menuElement.getSubElements();
for (MenuElement subElement : subElements)
{
attachActionListener(subElement, actionListener);
}
}
@Override
public void setMenuEnabled(String path, boolean enabled) {
path = mapping(path);
if (path.equals("_") || path.startsWith("_/")) {
return;
}
MenuElement menu = menuElements.get(path);
if (menu == null) {
throw new IllegalArgumentException("Menu " + path + " does not exist");
}
if (menu instanceof JMenuBar) {
((JMenuBar) menu).setEnabled(enabled);
} else if (menu instanceof JMenu) {
((JMenu) menu).setEnabled(enabled);
} else if (menu instanceof JMenuItem) {
((JMenuItem) menu).setEnabled(enabled);
} else {
throw new IllegalArgumentException(path + " is not a menu");
}
}
private static void appendMenuItem(Component menuItem, StringBuilder builder, String indent) {
if (menuItem instanceof JMenuBar) {
appendMenuSubElements((MenuElement)menuItem, builder, indent);
} else if (menuItem instanceof JPopupMenu) {
appendMenuSubElements((MenuElement)menuItem, builder, indent);
} else if (menuItem instanceof JMenuItem) {
builder.append(NEWLINE);
builder.append(indent);
builder.append(((JMenuItem)menuItem).getText());
builder.append(((JMenuItem)menuItem).isEnabled() ? "" : "[Disabled]");
appendMenuSubElements((JMenuItem)menuItem, builder, "| " + indent);
} else if (menuItem instanceof JSeparator) {
builder.append(NEWLINE);
builder.append(indent);
builder.append("--------");
}
}
/** Open all menus in menubar
* @param menu to be visited */
public static void visitMenuBar(JMenuBar menu) {
MenuElement[] elements = menu.getSubElements();
JMenuBarOperator op = new JMenuBarOperator(menu);
for (int k = 0; k < elements.length; k++) {
if (elements[k] instanceof JMenuItem) {
op.pushMenu(((JMenuItem) elements[k]).getText(), "/", true, true);
try {
op.wait(200);
} catch (Exception e) {
}
}
}
}
@Override
public void addSeparator(String parentPath) {
parentPath = mapping(parentPath);
if (parentPath.equals("_") || parentPath.startsWith("_/")) {
return;
}
if (!menuElements.containsKey(parentPath)) {
throw new IllegalArgumentException("Menu does not exist: " + parentPath);
}
MenuElement parent = menuElements.get(parentPath);
if (parent instanceof JMenu) {
((JMenu) parent).addSeparator();
} else {
throw new IllegalArgumentException("Not a menu: " + parentPath);
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed() && ev.getKeyCode() != KeyEvent.VK_ALT) {
// mnemonic combination, it's consumed, but we need
// set altKeyPressed to false, otherwise after selection
// component by mnemonic combination a menu will be open
altKeyPressed = false;
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
void altPressed(KeyEvent ev) {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length > 0 && ! (path[0] instanceof ComboPopup)) {
msm.clearSelectedPath();
menuCanceledOnPress = true;
ev.consume();
} else if(path.length > 0) { // We are in ComboBox
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
ev.consume();
} else {
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
JMenuBar mbar = root != null ? root.getJMenuBar() : null;
if(mbar == null && winAncestor instanceof JFrame) {
mbar = ((JFrame)winAncestor).getJMenuBar();
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if(menu != null) {
ev.consume();
}
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed() && ev.getKeyCode() != KeyEvent.VK_ALT) {
// mnemonic combination, it's consumed, but we need
// set altKeyPressed to false, otherwise after selection
// component by mnemonic combination a menu will be open
altKeyPressed = false;
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
@Override
public void finishMenu(String path) {
path = mapping(path);
if (path.equals("_") || path.startsWith("_/")) {
return;
}
if (!menuElements.containsKey(path)) {
throw new IllegalArgumentException("Invalid menu: " + path);
}
if (path.startsWith("/file/recent")) {
return;
}
MenuElement me = menuElements.get(path);
if (me instanceof JMenu) {
JMenu jm = (JMenu) me;
if (jm.getMenuComponentCount() == 1) {
String parentPath = path.contains("/") ? path.substring(0, path.lastIndexOf('/')) : "";
MenuElement parMe = menuElements.get(parentPath);
JMenuItem mi = (JMenuItem) jm.getMenuComponent(0);
jm.remove(mi);
if (parMe instanceof JMenu) {
JMenu parMenu = (JMenu) parMe;
parMenu.remove(jm);
parMenu.add(mi);
} else if (parMe instanceof JMenuBar) {
JMenuBar parMenuBar = (JMenuBar) parMe;
parMenuBar.remove(jm);
parMenuBar.add(mi);
}
}
}
}
@Override
public void actionPerformed( ActionEvent e ) {
JMenuBar menuBar = (JMenuBar) e.getSource();
JMenu menu = menuBar.getMenu( 0 );
if( menu != null ) {
MenuSelectionManager.defaultManager().setSelectedPath( SystemInfo.IS_WINDOWS
? new MenuElement[] { menuBar, menu }
: new MenuElement[] { menuBar, menu, menu.getPopupMenu() } );
FlatLaf.showMnemonics( menuBar );
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed() && ev.getKeyCode() != KeyEvent.VK_ALT) {
// mnemonic combination, it's consumed, but we need
// set altKeyPressed to false, otherwise after selection
// component by mnemonic combination a menu will be open
altKeyPressed = false;
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
void altPressed(KeyEvent ev) {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length > 0 && ! (path[0] instanceof ComboPopup)) {
msm.clearSelectedPath();
menuCanceledOnPress = true;
ev.consume();
} else if(path.length > 0) { // We are in ComboBox
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
ev.consume();
} else {
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
JMenuBar mbar = root != null ? root.getJMenuBar() : null;
if(mbar == null && winAncestor instanceof JFrame) {
mbar = ((JFrame)winAncestor).getJMenuBar();
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if(menu != null) {
ev.consume();
}
}
}
@Override
public boolean isMenuChecked(String path) {
path = mapping(path);
MenuElement menu = menuElements.get(path);
if (menu == null) {
throw new IllegalArgumentException("Menu " + path + " does not exist");
}
if (menu instanceof JCheckBoxMenuItem) {
return ((JCheckBoxMenuItem) menu).isSelected();
} else if (menu instanceof JRadioButtonMenuItem) {
return ((JRadioButtonMenuItem) menu).isSelected();
} else {
throw new IllegalArgumentException(path + " is not selectable menu item");
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed()) {
// do not manage consumed event
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
void altPressed(KeyEvent ev) {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length > 0 && ! (path[0] instanceof ComboPopup)) {
msm.clearSelectedPath();
menuCanceledOnPress = true;
ev.consume();
} else if(path.length > 0) { // We are in ComboBox
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
ev.consume();
} else {
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
JMenuBar mbar = root != null ? root.getJMenuBar() : null;
if(mbar == null && winAncestor instanceof JFrame) {
mbar = ((JFrame)winAncestor).getJMenuBar();
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if(menu != null) {
ev.consume();
}
}
}
void altPressed(KeyEvent ev) {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length > 0 && ! (path[0] instanceof ComboPopup)) {
msm.clearSelectedPath();
menuCanceledOnPress = true;
ev.consume();
} else if(path.length > 0) { // We are in ComboBox
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
ev.consume();
} else {
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
JMenuBar mbar = root != null ? root.getJMenuBar() : null;
if(mbar == null && winAncestor instanceof JFrame) {
mbar = ((JFrame)winAncestor).getJMenuBar();
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if(menu != null) {
ev.consume();
}
}
}
private static void setActionsMenu(JDialog dialog, MenuElement menu) {
MenuElement[] subItems = menu.getSubElements();
InputMap inputMap = dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
for (MenuElement menuElement : subItems) {
if (menuElement instanceof JMenuItem) {
final JMenuItem menuItem = (JMenuItem) menuElement;
if (menuItem.getAccelerator() != null) {
String key = "hackAction" + counter++;
inputMap.put(menuItem.getAccelerator(), key);
if (menuItem.getAction() == null) {
dialog.getRootPane().getActionMap().put(key,
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
menuItem.doClick();
}
});
} else {
dialog.getRootPane().getActionMap().put(key,
menuItem.getAction());
}
// System.out.println(key + " : "
// + menuItem.getText()+ " : "
// + menuItem.getActionCommand() + " : "
// + menuItem.getAccelerator() + " : "
// + menuItem.getAction());
}
}
// the original code had an else condition here, which is wrong.
// JMenu is a subclass of JMenuItem, which prevents sub-menus from being traversed.
if (menuElement.getSubElements().length > 0) {
setActionsMenu(dialog, menuElement);
}
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed()) {
// do not manage consumed event
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
@Override
public void addMenuItem(String path, String title, String icon, ActionListener action, int priority, final ActionListener subLoader, boolean isLeaf, HotKey key, boolean isOptional) {
path = mapping(path);
menuHotkeys.put(path, key);
menuActions.put(path, action);
if (!isLeaf) {
//action is ignored
addMenu(path, title, icon, subLoader);
return;
}
if (path.startsWith("_/")) {
return;
}
String parentPath = "";
if (path.contains("/")) {
parentPath = path.substring(0, path.lastIndexOf('/'));
}
MenuElement parentMenu = menuElements.get(parentPath);
if (parentMenu == null) {
throw new IllegalArgumentException("Parent menu " + path + " does not exist");
}
JMenuItem menuItem = new JMenuItem(title);
if (icon != null) {
menuItem.setIcon(View.getIcon(icon, 16));
}
if (action != null) {
menuItem.addActionListener(action);
}
if (key != null) {
menuItem.setAccelerator(KeyStroke.getKeyStroke(key.key, key.getModifier()));
}
if (parentMenu instanceof JMenu) {
((JMenu) parentMenu).add(menuItem);
} else {
throw new IllegalArgumentException("Parent path " + path + " is not a menu");
}
menuElements.put(path, menuItem);
}
void altPressed(KeyEvent ev) {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length > 0 && ! (path[0] instanceof ComboPopup)) {
msm.clearSelectedPath();
menuCanceledOnPress = true;
ev.consume();
} else if(path.length > 0) { // We are in ComboBox
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
ev.consume();
} else {
menuCanceledOnPress = false;
WindowsLookAndFeel.setMnemonicHidden(false);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
JMenuBar mbar = root != null ? root.getJMenuBar() : null;
if(mbar == null && winAncestor instanceof JFrame) {
mbar = ((JFrame)winAncestor).getJMenuBar();
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if(menu != null) {
ev.consume();
}
}
}
public boolean postProcessKeyEvent(KeyEvent ev) {
if(ev.isConsumed() && ev.getKeyCode() != KeyEvent.VK_ALT) {
// mnemonic combination, it's consumed, but we need
// set altKeyPressed to false, otherwise after selection
// component by mnemonic combination a menu will be open
altKeyPressed = false;
return false;
}
if (ev.getKeyCode() == KeyEvent.VK_ALT) {
root = SwingUtilities.getRootPane(ev.getComponent());
winAncestor = (root == null ? null :
SwingUtilities.getWindowAncestor(root));
if (ev.getID() == KeyEvent.KEY_PRESSED) {
if (!altKeyPressed) {
altPressed(ev);
}
altKeyPressed = true;
return true;
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
if (altKeyPressed) {
altReleased(ev);
} else {
MenuSelectionManager msm =
MenuSelectionManager.defaultManager();
MenuElement[] path = msm.getSelectedPath();
if (path.length <= 0) {
WindowsLookAndFeel.setMnemonicHidden(true);
WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor);
}
}
altKeyPressed = false;
}
root = null;
winAncestor = null;
} else {
altKeyPressed = false;
}
return false;
}
/**
* Maps {@code JPopupMenu.getSubElements()} through queue
*/
public MenuElement[] getSubElements() {
return ((MenuElement[]) runMapping(new MapAction<Object>("getSubElements") {
@Override
public Object map() {
return ((JPopupMenu) getSource()).getSubElements();
}
}));
}
/**
* Maps
* {@code JPopupMenu.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)}
* through queue
*/
public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) {
runMapping(new MapVoidAction("processMouseEvent") {
@Override
public void map() {
((JPopupMenu) getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager);
}
});
}
/** Open all menus in menubar
* @param menu to be visited */
private static void visitMenuBar(JMenuBar menu) {
JMenuBarOperator op = new JMenuBarOperator(menu);
for (MenuElement element : menu.getSubElements()) {
if (element instanceof JMenuItem) {
op.pushMenu(op.parseString(((JMenuItem) element).getText(), "/"), new DefaultStringComparator(true, true));
try {
op.wait(200);
}catch(Exception e) {}
}
}
}
/**
* Maps {@code JMenuItem.getSubElements()} through queue
*/
public MenuElement[] getSubElements() {
return ((MenuElement[]) runMapping(new MapAction<Object>("getSubElements") {
@Override
public Object map() {
return ((JMenuItem) getSource()).getSubElements();
}
}));
}
private boolean isMenuItemSelected() {
MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath();
return selectedPath != null && selectedPath.length > 0 &&
/* Make sure the selection is in the main menu bar, not just a context menu
somewhere. */
selectedPath[0] == menuBar;
}
/**
* Maps {@code JMenuBar.getSubElements()} through queue
*/
public MenuElement[] getSubElements() {
return ((MenuElement[]) runMapping(new MapAction<Object>("getSubElements") {
@Override
public Object map() {
return ((JMenuBar) getSource()).getSubElements();
}
}));
}
@Override
public void setMenuChecked(String path, boolean checked) {
path = mapping(path);
MenuElement menu = menuElements.get(path);
if (menu == null) {
throw new IllegalArgumentException("Menu " + path + " does not exist");
}
if (menu instanceof JCheckBoxMenuItem) {
((JCheckBoxMenuItem) menu).setSelected(checked);
} else if (menu instanceof JRadioButtonMenuItem) {
((JRadioButtonMenuItem) menu).setSelected(checked);
} else {
throw new IllegalArgumentException(path + " is not selectable menu item");
}
}