Passing accelerator keystrokes to the main menu in Java - java

I have added some accelerators to the main menu, using MenuItem.setAccelerator(). Just basic stuff like ctrl-c for copy, etc.
This works ok. But the app is a bit like an IDE, it has several panels containing JTables. If a table cell has focus, it absorbs the accelerator key, which means the main menu never sees it.
Clearly, if an editable table cell is active I would like the cut and paste keys to function normally, but in every other case I would like the main menu to respond.
Any ideas?

KeyStrokes go to the component that has focus first. Since JTable binds Ctrl+C to an Action, that action is invoked.
If you don't like the default Action of the table, then you would need to remove the binding from the table.
Read the section from the Swing tutorial on How to Use Key Bindings. It shows you how to remove a binding.

Thanks, that got me on the right track.
Removing the bindings didn't quite work, it just stopped the table doing its default action so the keypress was ignored altogether.
However, adding this to the table itself worked ok:
component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), "copy");
component.getActionMap().put("copy", actions.copyAction);
(Repeated for each desired key of course). Needs to be kept in synch with any changes to the main menu itself, but I can't see a way to avoid that with any method.

Related

Java swing requestFocusInWindow()

I know there are many questions on how to focus on a certain text field and so on, but it seems that the issue I am facing is a bit different. So, I have a JTextField which has functionality to autocomplete the text if something that is currently in it has been typed before by the user. I also have a set of buttons that perform insertion of some predefined portion of text into the text field when pressed. The problem is that every time any new text appears in the text field, the autocomplete can trigger and append the text that was used by the user previously. In order to it more friendly, I decided to select the part appended by the autocomplete. All the code is executed in the ED thread. Consider the case when the text field was not in focus :
Both code samples are in the actionPerformed method of the button.
// does not work
if (textField.requestFocusInWindow()) {
textField.getDocument().insertString(...);
}
The insertString() is overriden and has all the logic to select appended string by the autocomplete. So, the only thing I need is that the text field is selected before the string is inserted.
I tried :
// does work
textField.requestFocusInWindow();
SwingUtilities.invokeLater(() -> {
textField.getDocument().insertString(...);
});
The official doc says :
The call to the requestFocusInWindow method initiates the focus transfer, but it does not immediately move the focus ...
This sort of makes sense, since to acquire the focus, a call must be made to the window manager of the clients operating system (that's how I understand that, correct me if I am wrong).
Is the second example working mainly because both events (getting focus and inserting the string) are added to the event queue and the insertion appears after the focus request (actually at the end of the queue) or am I missing something? Is it a valid solution? Can it be done better?
Note: simply adding a listener to the text field ( to react when it is in focus) is not a solution, since the logic I described here is only a part of the whole functionality used.

Remove/disable/override Swing's focus traversal keys

Note: see the edit (save some time reading)
I'm trying to make my mind-mapping program respond to shortcuts like CTRL+RIGHT (reordering nodes) and TAB (insert child at next indent level). I have a JPanel that handles all of the keystrokes. It resides inside of a JTabbedPane that might be the cause for Key Bindings not working. I've chickened out and decided to just use KeyListener.
The problem is that with the aforementioned key combinations, Swing automatically shifts the focus to some other component. I'd rather not manually put setFocusable(false) everywhere. How can I disable these shortcuts altogether in such a way that the focus will not be shifted, and the relevant KeyEvents will still be sent to my JPanel?
Edit:
I used the following code:
for (int id : new int[] {KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS})
setFocusTraversalKeys(id, Collections.EMPTY_SET);
to disable the default traversal keys (particularly TAB.)
Now the issue is actually why CTRL+UP causes a loss of focus. When pressing CTRL+DOWN, for instance, it's fine. The component behaves as expected. But with CTRL+UP, it works as expected and then focus is shifted/lost somehow. Can anyone say what CTRL+UP means and how to disable it wherever it is? Google isn't helping.
KeyBinding are used for all KeyEvents implemented in Swing APIs, maybe there is/are conflict
is required to override required KeyBindings, change used Keys, set to null, e.i. depends of your requirements
list of KeyBindings by #camickr

Get Notified when component is invalidated or a repaint is fired

I want to get my event listener called when the component is repainted (JComponent). I read about different Event Listeners but none seems to be the correct one for Invalidate or Repaints. Any way to do this?
Why I want this: I'm trying to get notified when there is some change in a control, in order to fire the method that tracks the changes (as in the file has changed, "do you want to save changes?").
Another use for this is for manually invoking the custom layout manager of a non-added-to-the-container-but-drawn component (this one is kind of complex, it's for a GUI editor program).
Why I want this: I'm trying to get notified when there is some change in a control, in order to fire the method that tracks the changes (as in the file has changed, "do you want to save changes?").
Normally, you track changes to an edited file in the GUI model class. Every time your model adds or removes a character, you set a dirty flag in the model that you check later.
Another use for this is for manually invoking the custom layout manager of a non-added-to-the-container-but-drawn component (this one is kind of complex, it's for a GUI editor program).
Your understanding of Swing appears to be backwards. The components don't drive the layout. The layout arranges the components.
Here's one example of a Swing character based text editor.
Here's a Stack Overflow question about a GUI builder editor.

JPanel not listening to key event when there is a child component with JButton on it

I'm working on a map editor for my college project. And I had a problem that the map panel is not listening key event while it should.
This happens when I add a ToolBarPane (which extends JPanel) with JComponent such as JButton, JComboBox that implements ActionListener on it AND the map panel (which extends the JPanel) together on to the Frame (I used BorderLayout). I have System.out.println statement to test if the key press is received, and it's not printing, if I remove the ToolBar, the key listener works again, so is the mouseListenner is disabled just like the keyListener, which means I can't handle press events etc, but the mouseListener works fine and I can still handle mouse move event.
Here is a screen shot how it works without the ToolBarPane
http://img684.imageshack.us/img684/3232/sampleku.png
note that you can use the mouse to put images on the map, you can also select images using the mouse just like a laser tool, and by pressing number key you can switch between different images, this works fine until I add the ToolBarPane which shows like this:
img291.imageshack.us/img291/8020/failve.png
(please add http before that, I can only post one hyperlink)
(I can't post images here because I'm a new user)
With the ToolBarPane on I was no longer able to handle the key event.
I guess it might by that the focus as been transferred to that panel somehow, but not sure at all.
Does and body know this and can help me out?
Thanks very much
I suggest you use the InputMap and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or something similar. Excerpt from How to Use Key Bindings:
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
The component contains (or is) the component that has the focus. This input map is commonly used for a composite component
That has worked very robustly for me. Have a look at my other post for more information and actual code examples:
Keyboard input for a game in Java
or this tutorial:
Swing: Understanding Input/Action Maps
You should NOT be using a KeyListener.
Swing was designed to use Key Bindings which is far more flexible. Check out my quick summary of Key Bindings which also includes a link to the Swing tutorial which conains far more detail.
(I can't post images here because I'm a new user)
An image doesn't help much anyway. If you need more help post your SSCCE which shows the problem (after trying the above suggestion).

Can multiple accelerators be defined for a JMenuItem?

I've a problem with setAccelerator(). Right now, I have the code that works for Ctrl+X for DELETE operation. I want to set the accelerator to Shift+Delete as well for same JMenuItem.
My code as follows:
JMenuItem item = new JMenuItem(menuText);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_X, KeyEvent.CTRL_MASK));
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, KeyEvent.SHIFT_MASK));
but this is working only for Shift+Delete operation. Seems it is overriding the Ctrl+X operation. Can we make both these keystrokes work at the same time?
Please guide.
Yes it can be done. Behind the scenes the setAccelerator() is just creating a Key Binding, however as you noticed the second binding replaces the first.
So, you need to create an Action (not an ActionListener) to add the to the menu item. Read the section from the Swing tutorial on How to Use Actions for more information. Now that you have created the Action, you can share the Action with another KeyStroke by manually creating a Key Binding. You can read the section from the Swing tutorial on How to Use Key Bindings for a detailed explanation. Or you can read my blog on Key Bindings which give some simple code examples.
This second binding will not show up on the menu item itself.
From: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/AWTEvent.html
The masks are also used to specify to which types of events an AWTEventListener should listen.
So you can combine the mask for two keys, but not the KeyEvents.
item.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_X, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK));
A workaround solution would be to catch the KeyEvent in the middle (after your component fired it, but before your listeners will act on it) and check, whether its one of the two combinations. Then fire one event, on which you programmatically agree to represent the action you wanted.
The second call indeed overrides the accelerator. If the method starts with set, there will be only one. If the method starts with add, you can have more than one (for example for a number of listeners).
If you want multiple keystrokes to do the same, I think you should add a keyListener to the top frame (or panel, dialog, ...) which invokes the action listeners added to the menuItem.

Categories