Re: How can a JFrame be aware of keys pressed within controls?
Leonardo Azpurua wrote:
I would greatly appreciate if you could modify my original code to improve
it by using generics and explain briefly (or in detail, if you prefer and
have the time) the advantages that it would bring to the solution.
The simple use of generics takes about five minutes to learn. You simply add
the base type for generic classes or methods within angle brackets (<>).
The fundamental insight for me about generics is that it comprises assertions
about type relationships, not instructions. I view it as a declarative (that
is, non-procedural) sub-language.
Check out the Javadocs for 'getFocusTraversalKeys()', which of course you
would have looked up anyway:
<http://java.sun.com/javase/6/docs/api/java/awt/Container.html#getFocusTraversalKeys(int)>
You will immediately observe that it returns 'Set<AWTKeyStroke>'. So you
simply use that same exact type, copy and paste, for the return value in your
own code, and voil??, you're using generics!
class ToggleEnter
{
public static void activate( Container c )
{
Set <AWTKeyStroke> forwardKeys =
c.getFocusTraversalKeys( KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS );
Set <AWTKeyStroke> newForwardKeys =
new HashSet <AWTKeyStroke> ( forwardKeys );
newForwardKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0) );
c.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys );
}
etc.
The advantage is increased type safety enforced at compile time.
For a time-efficient enhancement of your generics knowledge, start with
<http://java.sun.com/docs/books/tutorial/extra/generics/index.html>
and the free PDF on the subject from /Effective Java/ by Joshua Bloch:
<http://java.sun.com/docs/books/effective/generics.pdf>
IBM DeveloperWorks also has excellent information:
<http://www.ibm.com/developerworks/search/searchResults.jsp?searchType=1&searchSite=dW&searchScope=javaZ&query=generics&Search=Search>
--
Lew