This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scrollbars AND Buttons

 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I 'implement' both the ActionListener and the AdjustmentListener in one class? I'm trying to simply have a Scrollbar and a Button in one class, but I only know to program for one or the other type per class.
Yes, I am a beginner.
Thank you for your help.
 
matt hooker
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Classes can implement multiple interfaces/listeners. just do like Class blah() implements listenerA, listenerB {
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You
 
rom chatterjee
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Previous answer perfectly correct. To complete the contract you have to implement the actionPerformed and adjustmentListener methods (as I am sure you are aware).
However if you have lots of buttons (you're not likely to have many scrollbars), you're actionPerformed method will have to identify which button was pressed and then take action. The problem with tihs is 2 fold:
1. The actionPerformed part of your code can be far removed from your button implementation.
2. Your actionPerfromed method can be quite large.
This is just awkward in terms of your code being easy to read and knowing what happens when an event occurs.
Another approach is to use an anonymous class. This is easier than it sounds. The code would look something like this:
Button okButton = new Button("OK");
okButton.addActionListener(/*anonymous inner class*/);
The next bit is to add the anonymous inner class. The code for the class is:
new ActionListener(){
public static void actionPerformed(ActionEvent e){
//...do something when okButton pressed
}
}
This has 2 parts. First create a new object - new ActionListeneter(), followed by the implementation of the actionPerformed method
okButton.addActionListener(new ActionListener(){
public static void actionPerformed(ActionEvent e){
//... do something here
}//end actionPerformed efinition
}//end anonymous class definition
);//end addActionListener method call
Your code doesnt need this kind of spacing or comments but I just did it this way to help make it easy to see what bracket is closing which part of code.
This approach mena you can add a whole range of event handlers at point of use
Rom
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic