We complete the task in this step, adding function that enables the program to catch keyboard events and draw them on the drawing panel. Note the use of themouseEnter
method to get the focus. This is necessary in order to direct the flow of keyboard events to the component where they can be processed.Example Applet
import java.applet.Applet; import java.awt.*; public class step4 extends Applet{ // adds text entry in drawPanel by handling keyDown events Button button = new Button ("Clear"); Panel buttonPanel = new Panel ( ); MyPanel2 drawPanel = new MyPanel2 (); public void init ( ){ drawPanel.setBackground (Color.white); button.setBackground (Color.green); button.setFont ( new Font ("Helvetica", Font.BOLD, 18) ); buttonPanel.add (button); setLayout (new BorderLayout ( ) ); add ("North", buttonPanel); add ("Center", drawPanel); } // end init public boolean action (Event event, Object arg) { if (event.target == button ) { return drawPanel.clear ( ); } // end if else return false; } // end action }// end step4 class MyPanel4 extends Panel { int last_x = 0; int last_y = 0; int x = 0; int y = 0; public boolean mouseDown ( Event event, int x, int y ) { last_x = x; last_y = y; return true; } // end mouseDown public boolean mouseDrag ( Event event, int x, int y ) { Graphics g = getGraphics ( ); g.drawLine ( last_x, last_y, x, y ); last_x = x; last_y = y; return true; } // end mosueDrag public boolean clear ( ) { Graphics g = getGraphics ( ); Rectangle r = this.bounds ( ); g.setColor ( this.getBackground ( ) ); g.fillRect ( 0, 0, r.width, r.height ); g.setColor ( this.getForeground ( ) ); return true; } // end clear public boolean mouseEnter ( Event event, int x, int y ) { requestFocus ( ); return true; } // end mouseEnter public boolean keyDown ( Event event, int key) { char next; next = (char)key; // cast int value of key last_x += 12; Graphics g = getGraphics ( ); g.drawString ( String.valueOf(next), last_x, last_y ); return true; } // end keyDown } // end MyPanel4Run the applet