File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes short cut in a JMenuItem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "short cut in a JMenuItem" Watch "short cut in a JMenuItem" New topic
Author

short cut in a JMenuItem

Mario A. Villamizar
Ranch Hand

Joined: Mar 14, 2002
Posts: 35
how can i set a short cut in a JMenuItem
e.g. F1 for help.
I try with setKeyStroke method but it respond to two arguments.
Thanks.


MA Villamizar
Ashish Mahajan
Ranch Hand

Joined: Feb 19, 2003
Posts: 77
Hi Mario,
Although javadocs of javax.swing.KeyStroke says it all but still use like this :-
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));

In short pass 0 for no modifiers.
As always this bloody Ashish has some suggestions :-
I have seen here lot of guys r directly adding action listeners, key strokes, mnemonics, etc. to the target component i.e. a tool bar button or menu item.
It is always better to put such values in Action and pass that action to the constructor of menu item/ tool bar button instead of setting such values of that component directly.
javax.swing.Action is a example of classic design pattern called "Command pattern". For small edu programs it's OK but for a real world application one should (should i say must) use Action.


The best teams have no specialists, only general contributors with special skills
Mario A. Villamizar
Ranch Hand

Joined: Mar 14, 2002
Posts: 35
thanks for the advice.
I am already applying actions combine with the command pattern, is very usefull.
but I have another problem now, when I run my application on windowsand I place the cursor over the tool bar, I got the tool tips that I seted in the class that I created extending tha AbstractAction class e.g., but whe I run my application on solaris (unix) and I place the cursor over the tool bar, the tool tip that I get is NAME and MNEMONIC_KEY . and what I am expecting is the SHORT_DESCRIPTION.
I don't know much about unix system.
what could be the problem?
Thanks.
Ashish Mahajan
Ranch Hand

Joined: Feb 19, 2003
Posts: 77
Hi Mario,
Glad 2 hear that u r using Actions.
Actually this won;t solve the probs u mentioned but just for a note :-
Am assuming that a unique action is shared by all the interested components. In short new actions r not created for both tool bar button and menu item. For this, the application frame should keep registry map of action name to it's action and clients (software components) should query for any action by name
OK back to point :-
Actually this should not happen. What happens internally is - since action is shared by say menu item, tool bar component, status bar field, etc. when we put any property in Action it fires property to all it's interested clients (menu items and buttons in their constructors regiters themselves as property change listeners to passed in action) After putting SHORT_DESCRIPTION in the tool bar, a property with the same name is fired and the intersted clients resets their properties e.g. JButton will reset it's tool tip in this case.
If it's not happening as expected then simply at the place where u r creating tool bar button set it's tool tip explicitly by setTooltipText(String) method with the text got from corrosponding action's SHORT_DESCRIPTION. That should solve ur prob
Actually the ans. would have been in one line, but i just thought to bore U.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Originally posted by Ashish Mahajan:
It is always better to put such values in Action and pass that action to the constructor of menu item/ tool bar button instead of setting such values of that component directly.

This does sound like a good solution, and as long as I have been programming SWING I have never used it. Could you provide me with a good reference for implementing this patturn?
Thanks.


GenRocket - Experts at Building Test Data
Ashish Mahajan
Ranch Hand

Joined: Feb 19, 2003
Posts: 77
Hi Gregg,
Am a very fond of Design Patterns and use it heavily while designing and coding. U may be knowing but still let me list few Design patterns book all these books include "Command" Pattern. Actually javax.swing.Action is also an example of another pattern namely "Observer" pattern.
1. The famous GoF (Gang of Four) Design Patterns book the best book of the last decade. Although they have used SmallTalk and C++ but still the best book on patterns.
2. [URL= http://www.amazon.com/exec/obidos/tg/detail/-/0471258393/103-1616972-9941458?vi=glance]Patterns in Java Vol. 1 by Mark Grand[/URL] Best Book. The author is one of my most favourite
3. Patterns in Java Vol. 2 by Mark Grand
4. Java Design patterns a tutorial by James Cooper Sorry i didn't like this much. I expected a lot but it's just normal book not a cracking. This book uses Java and UML so it may be of help also.
Well there other good books also.
For a complete list of design patterns info, visit
Ashish Mahajan
Ranch Hand

Joined: Feb 19, 2003
Posts: 77
Hi Gregg,
Let me bore ya more on the power of using Actions cause perhaps i won;t be around much from 2Morrow in the favour of server side computing.
Although in the pattern books u'll get the power of Actions as supporting undo-redo operations, decoupling the object that invokes the operation from the one that knows how to perform it etc..., swing's Action is an example of another perhaps the most powerful pattern, "Observer" pattern.
I can't imagine programming without "Observer" pattern. All the listener stuff are the example of "Observer" pattern. The power comes form the fact that the client (Observer) doesn't have to watch other constantly for any result. It can carry on with it's work and when something interesting happens the Observable (publisher) notifies the client (Subscriber) about the change with necessary info so that the client can update itself.
To recognise this power in general life - U know right now am searching for a server side job. I have registered to lot of job related sites. Now instead of checking those sites after every XXX time to check whether there r any mathced jobs or not (and many a times not getting any result) is really wastage of valuable time and is also painful to me. Instead of this if the job sites automatically delivers mathed jobs directly to my mail box (event notification) that way i can carry on my day to day work (no need to check job sites every now and then).
In programming scenario :- Let's assume that we r designing a text editor. Now any action can appear at any places say a menu item, a tool bar button or status bar field, or may be other custom comp or any other comp that may come in future. We need to always make sure that the staes of different component representing the same action should be same at any time. E.g. a ReadOnlyAction. The text editor can be set to read only mode from say menu item or the opended file itself can be a Read only. Now as soon as the editor becomes readonly all the component's (representing readonly action) icon's should be changed to represent the ReadOn-ReadOff state. Now if we don;t use Actions here then we will have to make sure that all the necessary component's icons remains synchronized at any time manually. A typical project has over hundread actions. It will be developer's nightmare to always make sure that the states r synchronized. Instead if we use Actions then all the synchronization will be automatic. A ReadOnlyAction in it's init method will add a property change listener (again "Observer" patterns) to the application frame's editor for namely "editable" property and will set it's icon according to the editor's state. After putting the SMALL_ICON property value in ReadOnlyAction all the components representing it will automatically update their icons.
Another example would be to enable/disable certain actions upon the document loaded/unloaded.
This is really powerful.
Thanx for bearing me.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

So is the Observable pattern that you mention something that has to be used explicitly along with Action Patterns? Or does Action Patterns subclass or implement Observable patterns and you can just use them that way?
I have read on Observable patterns before, the problem is that all the examples I see don't introduce examples like you stated. So it is hard for me to take them over to a SWING example. If you know of a simple SWING example that implements that patterns you described, could you provide me a link?
thanks. And you don't BORE me. I like reading your responses. They are very clear and informative. Thanks.
Ashish Mahajan
Ranch Hand

Joined: Feb 19, 2003
Posts: 77
Hi Gregg,
Sorry 4 late reply. Was relaxing a bit. I was not clear last time. This time i will try 2 b clear.
So is the Observable pattern that you mention something that has to be used explicitly along with Action Patterns? Or does Action Patterns subclass or implement Observable patterns and you can just use them that way?

I will just say few stuff. One can say, Observer == listener pattern. In short, if one uses Listeners in coding then we can say that he has used "Observer" pattern. When we design systems, we distribute the responsibilities among different classes like Managers, general clasees, Utility classes, etc.. and expect that they will on their own communicate with each other thru event notification mechanism. (And we r dammn sure about their behaviour cause they r not bloody egoist humans.) Now the classes which provide service (can be any class) should notify interested clients thru event notification. AbstractAction does this thru foll. API :-
1. addPropertyChangeListener(PropertyChangeListener)
2. removePropertyChangeListener(PropertyChangeListener)
and other related methods like getPropertyChangeListeners
When we pass Action to JButton or JMenu it calls it's setAction method which adds a property change listener if not added and configures it's properties according to the passed in action. (See the AbstractButton.java src code)
AbstractAction has getValue() putValue() methods. If any client puts any property (can be a standard defined in Action interface or any custom property) by putValue() then the AbstractAction fires a property describing that key-value. Now the resgietsred clients r the buttons and menu items or any other components like status bar fields. They quickly update their properties from the propertyChangeEvent. The code to do this is naturally in parent AbstractButton class. This class updates itself for the known properties defined in Action interface (like NAME, SMALL_ICON, etc..). So is achieved synchronization. One point to b noted is that :- Although the synchronization of buttons and menu items properties is automatic for the developer (cause Sun guys have done it 4 us in AbstractButton) there can be other components where the actions should be used e.g. Status bar field. In status bar any action can come cause the user can customize the status bar components thru customization if provided. So it's better to write StatusBarField component which will have almost API like AbstractButton like constructor accepting Action (same as JButton or menu item), setAction, and configurePropertiesFromAction etc.. Also not all the status bar fields should accept Action e.g. the field used for displying description has nothing 2 do with Actions. So the designer should design accordingly.
I have read on Observable patterns before, the problem is that all the examples I see don't introduce examples like you stated. So it is hard for me to take them over to a SWING example.

Actually i haven't read such examples from any book. I just try to study the existing designs in general life as well as in computing. There r lots of interesting examples. e.g. regarding the computing design. One more example about the "Observer" pattern would be Client-server chat. Instead of two clients constantly asking the server whether there is any message from other chatters (and many a times get upset) while the chatter logs in it should register with the server and any chatter just sends message to sever and that server will have handles of all the chatters and will notify all the other chatters. I have heard from my friend that some messangers constantly (in while(true) loop) queries server about other chatter's message etc. God bless such designers
About the example in general life. U know i never give my company's mail id to anybody (or if i give i also give one more default mail id as fallback) the reason being that by doing so i am exposing the internal details i.e. the company name (not following the "data encapsulation" design principle) . When i will join other company all my friends now will have to update their Address book just because i have joined a new company. Had that mail id from say yahoo then that will work till the rest of my life.
If you know of a simple SWING example that implements that patterns you described, could you provide me a link?

I don;t have any links. But i will HIGHLY RECOMMEND the Core JFC by Kim Topley. This is the best book on swing. The author has more than 30 yrs experience in GUI building/designing. Study carefully how he approaches the solution of any prob. He approach is the best, slowly by slowly step by step.
Best Wishes,
Ashish
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: short cut in a JMenuItem
 
Similar Threads
Brain dumps
JLS
JDesktopPane creates inner frame menuItem actionPerformed does not.
Problem with JTabbed pane focus
Help Please Urgent