You need to put controls/components on the display, and then have code - event handlers - that will "catch" events such as mouse clicks or key presses | |
The display is handled by a layout manager. | |
Overall, the following code will create a label, will have the layout manager put it onto the display in the top/"North" section, and the mouseMove event will cause the X and Y coordinates of the mouse cursor to be displayed in the label. | |
First, note that the paint event will cause the string "Hello" to be displayed at location 50,50 from the upper left corner of the applet's display area. If you get ambitious, change the commented lines in paint so that you can see the ovals, rectangles, and lines. import java.applet.*; | |
When a mouse Up event is detected, the display area background will be made red -- |
public boolean mouseUp(Event e, int x, int y)
{
// TODO: Add your own implementation.
// OLD GENERATED CODE: return super.mouseUp(e,x,y);
// OUR NEW CODE -
setBackground(Color.red);
repaint();
return true;
}
When a mouse Down event occurs, the background
will be made green -- | |
Add the label called mousePositionLbl and the mouseMove event handler -- | |
// We're adding
a label to the applet, ... | |
And modify init (called when the applet is initialized) to select a layout manager and to use it via the add to place the label on the display - |
public void init()
{
// TODO: Add your own implementation. FROM J++: super.init();
// our code -- to add a BorderLayout manager,
// and then to add a label to the layout
//
setLayout(new BorderLayout());
add("North", mousePositionLbl);
}
} /* end of applet */
![]()
Created &
Maintained by DrB - Comments welcome.
Last edited on Friday, July 30, 2004