Reputation: 1488
I've started learning about event handlers and have tried to play around with some basic concepts. I have gotten a weird error in the following code. I'm using Eclipse and get the following errors on the line where I try to add an ActionListener to the Button b:
"The method addActionListener(ActionListener) in the type Button is not applicable for the type new ActionAdapter(){}"
"ActionAdapter cannot be resolved to a type"
import java.awt.*;
import java.awt.event.*;
public class Test extends Frame{
private TextField text = new TextField(20);
Button b;
private int num_clicks = 0;
public static void main(String args[]){
Test appwind = new Test("title");
appwind.setSize(300,300);
appwind.setTitle("Irrelevant");
appwind.setVisible(true);
}
public Test(String title)
{
super(title);
setLayout(new FlowLayout());
addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e) {
System.exit(0);}});
b = new Button("Click");
add(b);
add(text);
b.addActionListener(
new ActionAdapter()
{
public void actionPerformed(ActionEvent e)
{
num_clicks++;
text.setText("number of times clicked: " + num_clicks);}
});
}
}
Upvotes: 0
Views: 3515
Reputation: 159784
Adapter classes are convenience classes provided when the underlying interface has 2 or more methods. ActionListener
only has one method - Use ActionListener
instead
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
}
});
Upvotes: 1