Reputation: 15
I wanted to create a JFrame
where it prints out on the console: "It works!!" when you click a JButton
. Below is the code:
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class CurrentlyMajorCodesCompiler extends JFrame {
public static void main (String args[]) {
CurrentlyMajorCodes CMC = new CurrentlyMajorCodes();
CMC.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class CurrentlyMajorCodes extends JFrame {
private JButton ClickSpeedTest;
private tensCPS TCPS;
public CurrentlyMajorCodes () {
super("Major Code Compiler");
setLayout(new FlowLayout());
ClickSpeedTest = new JButton("Click Speed Test");
add(ClickSpeedTest);
ClickSpeedTest.addActionListener(new MouseAdapter () {
public void mouseClicked (MouseEvent event) {
System.out.println("It works!!");
}
});
setSize(250, 250);
setVisible(true);
}
}
However, at: ClickSpeedTest.addActionListener
, it gives me an error saying:
The method addActionListener(ActionListener) in the type
AbstractButton is not applicable for
the arguments (new MouseAdapter(){})`
I don't understand what it's trying to communicate, because I never used an AbstractButton
in the code, and don't know what it even is. Can someone please help?
Upvotes: 0
Views: 865
Reputation: 20914
Method addActionListener() in class AbstractButton
takes a single parameter, namely an instance of a class that implements interface ActionListener. Class JButton
extends AbstractButton
and therefore inherits this method.
Now look at class MouseAdapter. You will see that it does not implement interface ActionListener
and therefore is not suitable as a parameter for method addActionListener()
.
For the requirement described in your question, I recommend creating your own implementation of interface ActionListener
. The following is similar to the code you posted and uses an anonymous inner class to implement interface ActionListener
:
ClickSpeedTest.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println("It works!!");
}
});
Note that the above actionPerformed()
method will be invoked whenever the button ClickSpeedTest
is activated, whether via the mouse or the keyboard or even via java code. (Refer to method doClick() in class AbstractButton
.)
If you are using Java 8 or above, then ActionListener
is a functional interface, i.e. an interface that contains precisely one abstract method and hence you can implement it using a lambda expression which means you could also use the following code:
ClickSpeedTest.addActionListener(e -> System.out.println("It works!!"));
Upvotes: 1
Reputation: 35061
MouseListener is different from ActionListener. You need to use the later
ClickSpeedTest.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent event) {
System.out.println("It works!!");
}
});
Upvotes: 1