In this step, we will process scrollbar events. Recall from the earlier discussion that the
Scrollbarclass receives the events initially. In the code, below, we will elect to process those events in the applet, itself. Thus, our applet class must implement theAdjustmentListenerinterface, and we will addselfas the recipient object for both scrollbars.In our
adjustmentValueChangedmethod -- the only method included in the interface -- our strategy will be to look for events whose source is an instance of theScrollbarclass. When we see one of them, we will check the particular object that generated the event to determine which scrollbar was moved. We then change the value of either an X- or Y-offset global variable that is used to adjust the portion of thecenterPanelthat is displayed.The following block of code does this; the only "processing" we do, however, is to print out a message identifying the current value of the selected scrollbar.
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class step4 extends Applet implements AdjustmentListener { // adds scrollbars MyFrame outerBox; Panel centerPanel; Panel bottomPanel; public void init ( ){ buildWindow (); } // end init //****************** buildWindow // *** Global variables for ui components MenuBar menuBar; Menu fileMenu; MenuItem fileNew, fileOpen, fileClose, fileSave, fileQuit; Menu editMenu; MenuItem editCut, editCopy, editPaste, editDelete; Menu helpMenu; MenuItem helpHelp; Scrollbar scrollbarV; Scrollbar scrollbarH; TextField message; //*********** buildWindow method ommitted here *********** //*********** Interface Methods *********** //**** AdjustmentListener method public void adjustmentValueChanged ( AdjustmentEvent e ) { Object s = e.getSource(); // *** process Scrollbar actions if ( s instanceof Scrollbar ) { if ( s == scrollbarV ) { System.out.println ( "Vertical scrollbar detected; value = "+e.getValue() ); offsetY = - scrollbarV.getValue(); } if ( s == scrollbarH ) { System.out.println ( "Horizontal scrollbar detected; value = "+e.getValue() ); offsetX = - scrollbarH.getValue(); } } // end process scrollbar actions } // end AdjustmentListener }// end step4If you ran the applet, you would, unfortunately, not be able to see the effects of moving the scrollbars. We address this problem in the next step by adding a very simple drawn object to the display.