In this step, we will process scrollbar events. Recall from the earlier discussion that the
Scrollbar
class 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 theAdjustmentListener
interface, and we will addself
as the recipient object for both scrollbars.In our
adjustmentValueChanged
method -- the only method included in the interface -- our strategy will be to look for events whose source is an instance of theScrollbar
class. 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 thecenterPanel
that 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(); drawSomething (); } if ( s == scrollbarH ) { System.out.println ( "Horizontal scrollbar detected; value = "+e.getValue() ); offsetX = - scrollbarH.getValue(); drawSomething (); } } // 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.