Java Reference
In-Depth Information
5. Nested classes can be public , private , or no modifier. Classes with no modifiers
can be accessed within the package. Public classes can be accessed from everywhere.
Private classes can be accessed only from within the outer class.
6. When inheriting from an interface that has multiple methods and we do not want to
override all of them, we can use the adapter class when present. The adapter class
has empty implementation of all the methods. For example, if we only care about the
mousePressed method, then our listener should inherit from the MouseAdapter class
instead of the MouseListener interface.
7. Every window can have at most one menu bar. Therefore, use the setJMenuBar
method to add the menu bar to the window.
8. Every menu bar can have multiple menus. Every menu can have multiple menu items.
Menu items are similar to buttons and an ActionListener can be registered with
9. It is possible to register multiple event listeners with the same event source. When
the event occurs, the event listeners will be notified in some random order.
10. Call setFocusable(true) inside the constructor of a panel in order to make the panel
focusable and allow key events to be registered with it.
10.8 Exercises
1. Write a program that prints Howdy! to the screen every 10 seconds. The program
should have only a single outer class with a main method that contains an anonymous
local class.
2. What is the difference between a KeyListener and a KeyAdapter ?
3. What is the difference between a MouseListener and a MouseMotionListener ?
4. Given a MouseEvent ,Javahasthe getButton and getModifiersEx methods for de-
termining which mouse buttons are pressed. Are both methods really needed, that is,
do they differ in any way?
5. White a program that creates a window with a menu bar. The menu bar should have
a single menu that has 10 menu items with text: 0, 1, ... , 9, respectively. When a user
selects a number from the menu bar, the corresponding number should be displayed
inside the panel of the window. Once finished, add a key listener. When a user types
a digit between 0 and 9, the digit should be displayed in the window. Create an array
to store the menu items.
6. Create a game that displays a filled circle. Add a mouse motion listener that keeps
track of the mouse movement. When the mouse cursor gets close to the circle, move
the circle to a new random location within the panel.
7. Write an application that has two menus. The first menu is used to choose a color: red,
green, or blue. The second menu contains the exit menu item. The user can use the
first menu to change the background panel color (use the setBackground method).
Search WWH ::

Custom Search