File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Scrollbars AND Buttons Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Scrollbars AND Buttons" Watch "Scrollbars AND Buttons" New topic

Scrollbars AND Buttons

Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
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.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
matt hooker
Ranch Hand

Joined: Jul 26, 2001
Posts: 46
Classes can implement multiple interfaces/listeners. just do like Class blah() implements listenerA, listenerB {

Its not what you do, its the way you say you've done it.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Thank You
rom chatterjee
Ranch Hand

Joined: Dec 11, 2001
Posts: 46
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){
// 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 Chatterjee<BR>Sun Certified Java Programmer
I agree. Here's the link:
subject: Scrollbars AND Buttons
It's not a secret anymore!