Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Action Listener Question

Status
Not open for further replies.

TheButcher

Programmer
Jul 6, 2001
11
US
need help! I'm having problems with ActionListener. I don't know how to have mulitiple action listeners in the same program. This is probably very easy to do but I'm fairly new to java (only new C before this program).

here is my program so far:

1) click on the applet and will create a numbered vertice
2) seperate frame has 3 text fields...vertice1, vertice2, weight.
3) click buton to create an edge between vertices with associated weight.

code snippets:

Button addEdge; //before init() section
addEdge = new Button("Add Edge") //within init()
addEdge.addActionListener(this); //within init()
public void paint
{
code here makes vertices
}
public void actionPerformed (ActionEvent event)
{
code here reads in #'s from text fields & connects graph
}


now here is the problem. I need to make another button that will traverse the edges when clicked. Unfortunately, all the examples in my java book only deals with using one action listener. It says action listener must be implemented and have to use this function that is automatically called. Can I still write another one using action listener?

Many Thanks, Butch
 
You have loads of choices: you could write another small class, call it myclass and make it implement ActionListener etc and then add it as an actionListener to the required component.
Or you could use an anonymous inner class like the example below.

<yourButton>.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
{
<your code>
}
}
);

Or you could just use the current actionlistener that you have (i.e. this) and just adapt the actionPerformed method to look out for when the other button is pressed as well i.e use an if to evaluate the action command used e.g.

if(e.getActionCommand().equals(&quot;<your button text>&quot;)

blah blah blah.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top