The Artima Developer Community
Sponsored Link

Java Answers Forum
adding an actionListener to a button, I need help!!

2 replies on 1 page. Most recent reply: Mar 13, 2002 1:53 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Rachel

Posts: 2
Nickname: rachel
Registered: Mar, 2002

adding an actionListener to a button, I need help!! Posted: Mar 13, 2002 12:29 AM
Reply to this message Reply
Advertisement
Please help me,

I need to add a button to my JPanel and when clicked it must take the user to another class in my application. Do I need to implement the addActionListener method to my code for this to happen, if so, then how do I do this and if not what must I do. Please help me.

Thanks Rachel


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: adding an actionListener to a button, I need help!! Posted: Mar 13, 2002 12:57 PM
Reply to this message Reply
You do have to add some kind of listener to your button.
The simplest is ActionListener

you can make the class you are working with an ActionListener by changeing the class declaration line and adding the key words
implements ActionListener

ad an import statement:

import java.awt.event.*;

and add the method

public void actionPerformed(ActionEvent ae){
//put your code you want the action listener to execute here
}

and then add a statement after you declare your button
with

buttonname.addActionListener(this);

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: adding an actionListener to a button, I need help!! Posted: Mar 13, 2002 1:53 PM
Reply to this message Reply
If you have an applet or form with only one control that will respond to actions, this is okay, but if you have multiple actions defined this way, I would suggest using an (anonymous, usually) inner class for each. Here is an example of an anonymous inner class that implements the ActionListner interface being created and added to a button:
        button.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent ae )
                {
                    model.addElement( new String(textField.getText()) );
                }
            } );

I sometimes do this with named (instead of anonymous) inner classes; usually when I want to use the same action on more than one control, or when the class is so large that it makes the syntax of the inner class unwieldy.

Flat View: This topic has 2 replies on 1 page
Topic: JSP and FORM authentication?? Previous Topic   Next Topic Topic: Printing in Java bu Dot Matrix Printer

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use