28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

456 Chapter 5 Keyboard Handling, Actions, and Scrolling<br />

Listing 5-1 Automatic focus handling (continued)<br />

public static void main(String[] args) {<br />

FocusExamplel f = new FocusExamplel();<br />

f .packO ;<br />

f.addWindowListener(new WindowAdapter() {<br />

public void windowClosing(WindowEvent evt) {<br />

System.exit(0);<br />

}<br />

});<br />

f.setVisible(true);<br />

}<br />

private JButton b; // The button<br />

private JTextField t; // The text field<br />

Run this program using the command<br />

j ava <strong>JFC</strong>Book.Chapters.FocusExamplel<br />

and try it without using the mouse. You will find that the text area is ready to<br />

receive input straight away, because the initial focus has been assigned to this<br />

component automatically. Now type something and press the return key and<br />

your text will appear on the caption bar. So far, so good. Now type some more<br />

into the text area. Suppose that you wanted to use the Clear button to discard<br />

the text you have just typed. With the mouse, you simply move the<br />

pointer over the button and click, but if you can't use the mouse, how can you<br />

get to the button?<br />

The focus can be moved between components by using Tab to go forward<br />

and Shift-Tab to move backward. In this case, since there are only two<br />

components, you can use either key to move to the button. When you get the<br />

focus onto the button, notice that it highlights itself—this is typical visual<br />

feedback when a component has the focus. Now that you're over the button,<br />

how do you "click" it? The JButton class is keyboard-aware: if you press the<br />

space bar, it acts as if you had clicked it with the mouse. Do this now and<br />

your text will disappear. To type some more text, just tab back to the text area<br />

and notice that the button loses its highlighting.<br />

Using the requestFocus Method<br />

What you have just seen was free functionality: the correct component got<br />

the focus when the application started and both components reacted prop-

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!