首先说明,无论接口是在类内部还是外部,都需要覆盖接口定义的所有方法。
至于原因就去查看java教材关于接口的那一章讲解。
一、当接口为内部时,在类的头部即public class YY 后不必写implements XX-interface
如:
public class J_Panel extends JPanel
{
public J_Panel()
{
addMouseListener(new MouseListener()
{
public void mouseExited(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
}
); // end of addMouseListener
addMouseMotionListener(new MouseMotionListener()
{
public void mouseMoved(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{}
}
); // End of addMouseMotionListener
} // End of the conductor of J_Panel
protected void paintComponent(Graphics g)
{
} // End of the function of paintComponent
}
注:若写上了implement MouseListener,
二、而当接口为外部时,必须在类的头部即public class YY 后写上implements XX-interface
如:
public class ScribblePanel extends JPanel implements MouseListener, MouseMotionListener
{
public ScribblePanel()
{
// Register listener for the mouse event
addMouseListener(this);
addMouseMotionListener(this);
}
// interface MouseListener
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mousePressed(MouseEvent e)
{}
// interface MouseMotionListener
public void mouseDragged(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{}
}