// Just use the following methods (mouseEnter, mouseDown, mouseUp ...) // in an Applet. You can check the Component class in java.awt for more // methods (mouseMove, mouseExit etc.) on handling mouse related events. The Component // class is the parent for most GUI components in Java. public class PBHeader extends java.applet.Applet implements Runnable { public void init() { // some code..... } public void start() { // some code..... } // more Methods ......... public boolean mouseDown(Event e, int x, int y) { // put code here to do stuff..... return true; } public boolean mouseEnter(Event e, int x, int y) { // put code here to do stuff..... return true; } public boolean mouseExit(Event e, int x, int y) { // put code here to do stuff..... return true; }
//The Component class in java.awt has methods to handle the focus. //You can use the gotFocus method to execute code when the component gets the focus. //For example , in the following code embedded in an applet, the status bar on the //browser (Netscape 2.0) shows the string "I have the FOCUS!!!" when the applet gets //focus. (by clicking on the applet) public class PBHeader extends java.applet.Applet { public void init() { // some code..... } public void start() { // some code..... } // more Methods ......... public boolean gotFocus(Event e, Object o) { // put code here to do stuff..... showStatus("I got the FOCUS"); return true; } // You can use the lostFocus (triggered when the component loses focus) method in the // same way. The requestFocus (the component can request focus using this method) // and nextFocus (shifts focus to another component) methods may also be explored.
A basic window/mouse application falls into the category of event driven programming. Like any event programming language (Windows SDK, X, PB, VB etc), java can trap and respond to system/user events.(Submitted by Carmen Delessio)The basic framework involves an event handler routine (like handleEvent() or action()) and the "other" code. The event handler routine is called whenever a user/system event occurs. It is also possible to force an application to respond to an event using certain methods (like postEvent(), deliverEvent()). Inside the event handler, the identity of the event can be ascertained using the Event attributes (like Event.id, Event.arg, Event.x, Event.y, Event.target etc etc - see the Event class in java.awt for details about the event attributes). The Component class also provides methods for some common user events like mouseDown, mouseUp, mouseMove and various other keyboard and mouuse events.
An example of a simple window/mouse (or "event driven" app) is given below. (Similar code can be found in practically _every_ java applet that uses any event trapping - nothing new in this code!!!!)
// What is the framework of the basic window/mouse application? // // The framework of an event driven app will comprise the following // 1. component definition and initialization (What buttons, // labels, TextAreas . . .) // 2. component function (What to do when component is clicked) // 3. Event processing to associate event with component function // The following code does this in a consistent manner. // This code could be generated! // There is a method called addPosition which adds the components at // a specified x,y location. Using absolute layout available at //http: //ugweb.cs.ualberta.ca/~nelson/java/source/AbsoluteLayout.java // A function is defined for each component // Events are associated with components by casting the target of // the event as a component. import java.awt.*; import java.util.*; import java.applet.Applet; public class test extends Applet { // define and intialize components , 1 text area and 3 buttons TextArea Text1 = new TextArea( "Initial Text ", 4, 41); Button Command1 = new Button( "One"); Button Command2 = new Button( "Two"); Button Command3 = new Button( "Three"); // addPosition adds Component at specified location protected void addPosition( Component c, int x, int y ) { add(c); c.move(x,y); } public void init() { // Using AbsoluteLayout to be able to position components AbsoluteLayout absolute = new AbsoluteLayout(); setLayout(absolute); setFont(new Font ("MS Sans Serif", Font.BOLD, 8)); resize (543 , 510 ); // Call addPosition for each coponent addPosition(Text1, 110,9); addPosition(Command1, 350,406); addPosition(Command2, 260,366); addPosition(Command3, 170,327); } // end init // have an action method for each component public void Command1_action(Object arg){ Text1.setText( arg.toString()); //more code here } public void Command2_action(Object arg){ Text1.setText( arg.toString()); //more code here } public void Command3_action(Object arg){ Text1.setText( arg.toString()); //more code here } // In action caste target to component and compare to components // call corresponding mmetod for component public boolean action(Event evt, Object arg ) { if (((Component) evt.target).equals(Command1)) { Command1_action(arg); } else if (((Component) evt.target).equals(Command2)) { Command2_action(arg); } else if (((Component) evt.target).equals(Command3)) { Command3_action(arg); } return true; } // end action public static void main(String args[]) { Frame f = new Frame("Button Framework Code Example"); test ex1 = new test(); ex1.init(); f.add("Center", ex1); f.pack(); f.resize(f.preferredSize()); f.show(); } }
Notice that paint() is called in two cases:repaint() is the method you use to have the system call update() with the current graphics context. By default, update() calls paint() after clearing the display, and so the applet is painted again.
- when the window is resized or de-iconified, or needs to be redrawn for obscure reasons (pun intended), and
- when you haven't overridden the default update() method.
The problem occurs when you need to display things moving around, but also need some static background. Calling repaint() and having update() perform your simple animation is the right solution, but the animation drawing should be separated from the background drawing. Putting the animation into update() (or a separate function called by update(), or double-buffering, ...), putting the background drawing routines into paint(), and calling repaint() is a good solution.
Some code should make things clear: draw one static line with one line moving ever rightwards below it:
/** * Our thread's run() method, called in response to thread.start() */ public void run() { Thread me = Thread.currentThread(); me.setPriority( Thread.MIN_PRIORITY ); // Be nice while(true) { repaint(); // This causes a call to update() to be scheduled ASAP try {me.sleep(100);} catch (InterruptedException e) {} } } /** * Draw the static top line * * NOTES * This is called whenever the frame has been hidden and should be * redisplayed. */ public void paint(Graphics g) { g.setColor( Color.gray ); g.drawLine( 0, 0, linewidth, 0 ); // we could put a call to update() (or whatever the animation drawing // routine is here) to redisplay the animation, but since it's // running and will be called soon anyway, there's no need. } /** * Draw the moving line. * * NOTES * This is called in response to a repaint() call. */ public void update(Graphics g) { /* undraw the old line */ g.setColor( Color.gray ); g.drawLine( x0, 1, x0 + width, 1 ); /* draw the new one, and perform bookkeeping */ x0 += 1; g.setColor( Color.red.brighter() ); g.drawLine( x0, lineheight, x0 + width, lineheight ); }
Peers are only needed if you are implementing the AWT. You can otherwise ignore them completely.(Submitted by Andrew Berkheimer)
The awt.peer class handles the specifics of how to implement a component on a specific OS platform. awt.peer.Button, for example, will display a button in the correct "style" for that OS, so that in Windows95 it looks like a normal Windows95 button, in Unix it looks like a normal Motif/etc button, etc. You don't need to worry about this unless you are porting the AWT to a new OS platform.
If you want to check whether the click is within one of several rectangular regions, define an array of rectangles, and override handleEvent(). For example, in the component constructor:
Rectangle r[] = new Rectangle[NO_OF_RECTANGLES]; ...construct each rectangle in the array, specifying coordinates relative to the component that these rectangular regions apply to...Then override handleEvent() for the component:public boolean handleEvent(Event e) { if (e.id == Event.MOUSE_DOWN) { // Determine which rectangle was selected for (int i = 0; i < NO_OF_RECTANGLES; i++) { if (r[i].inside(e.x, e.y)) { // This is the rectangle selected System.out.println("You selected rectangle no. " + i); } } return true; } return super.handleEvent(e); }Note: I have not compiled this code, but it should work!
To get the size and resolution of the display, useTo get the size of a component (e.g. an applet, or a frame), use size().Component.getToolkit().getScreenResolution() Component.getToolkit().getScreenSize()
All you need to do is make a reference to one component available to the other, and call repaint() on the component reference. For example:// Define a canvas class class C extends Canvas { public C() { resize(100, 100); // if it has no size, you can't see it! } } // Define a button that controls the canvas class B extends Button { C cref; public B(C c) { cref = c; // store a reference to the canvas this // button controls } public boolean handleEvent(Event e) { if (e.id == Event.ACTION_EVENT) { // when the button is pressed, cause the canvas // to be repainted cref.repaint(); return true; } return super.handleEvent(e); } } // Define a container which instantiates both of these components class A extends Applet { C a; B b; public void C() { add(c = new C()); // instantiate the canvas add(b = new B(c)); // instantiate the button } }