import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame implements MouseListener
{
JFrame f;
JPanel p;
JButton b;
test()
{
f=new JFrame("My Frame");
p=new JPanel();
f.add(p);
b=new JButton("Button");
p.add(b);
f.setSize(100,100);
f.setVisible(true);
b.addMouseListener(new MouseListener()
{
public void mouseClicked(MouseEvent ae)
{
System.out.print("mouse clicked");
}
});
b.addMouseListener(new MouseListener()
{
public void mouseEntered(MouseEvent ae)
{
System.out.print("mouse Entered");
}
});
b.addMouseListener(new MouseListener()
{
public void mouseExited(MouseEvent ae)
{
System.out.print("mouse Exited");
}
});
b.addMouseListener(new MouseListener()
{
public void mousePressed(MouseEvent ae)
{
System.out.print("mouse Pressed");
}
});
b.addMouseListener(new MouseListener()
{
public void mouseReleased(MouseEvent ae)
{
System.out.print("mouse Released");
}
});
}
public static void main(String args[])
{
new test();
}
}
错误如下:
--------------------Configuration: <Default>--------------------
C:\Users\SHUBHENDU\Documents\test.java:19: <anonymous test$1> is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
{
^
C:\Users\SHUBHENDU\Documents\test.java:26: <anonymous test$2> is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
{
^
C:\Users\SHUBHENDU\Documents\test.java:33: <anonymous test$3> is not abstract and does not override abstract method mouseEntered(java.awt.event.MouseEvent) in java.awt.event.MouseListener
{
^
C:\Users\SHUBHENDU\Documents\test.java:40: <anonymous test$4> is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
{
^
C:\Users\SHUBHENDU\Documents\test.java:47: <anonymous test$5> is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
{
^
5 errors
答案 0 :(得分:4)
如果您有一个具体的Java类(非抽象类),您必须实现接口所具有的所有方法,当然,如果您的类实现了该接口。
因此将MouseListener
接口的未实现方法添加到您的代码中。但是每次都在同一个按钮上添加一个新的MouseListener
。这不是它的使用方式。您可以/应该在同一代码体中实现所有MouseListener
方法。 删除多余的MouseListener
个JButton b
。
答案 1 :(得分:2)
我对AWT并不熟悉,但看起来你有一个非抽象类(test
),它没有实现接口的抽象方法(MouseListener
)。
http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
您需要实施:
mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
如果您的类 是抽象的,那么您将不需要实现这些方法(onus将在下一个非抽象子类上执行)。
答案 2 :(得分:2)
如果您只想覆盖MouseListener
界面的一种方法,可以使用MouseAdapter
,如下所示:
JButton button = new JButton("Click");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouse was clicked");
}
});
答案 3 :(得分:1)
修复这些错误......
1) Remove "implements MouseListener"
2) Change MouseListener to MouseAdapter