📅  最后修改于: 2020-09-29 05:37:03             🧑  作者: Mango
Java适配器类提供了侦听器接口的默认实现。如果继承适配器类,则不会被迫提供所有侦听器接口方法的实现。这样就节省了代码。
适配器类可在java.awt.event,java.awt.dnd和javax.swing.event包中找到。适配器类及其相应的侦听器接口如下所示。
Adapter class | Listener interface |
---|---|
WindowAdapter | WindowListener |
KeyAdapter | KeyListener |
MouseAdapter | MouseListener |
MouseMotionAdapter | MouseMotionListener |
FocusAdapter | FocusListener |
ComponentAdapter | ComponentListener |
ContainerAdapter | ContainerListener |
HierarchyBoundsAdapter | HierarchyBoundsListener |
Adapter class | Listener interface |
---|---|
DragSourceAdapter | DragSourceListener |
DragTargetAdapter | DragTargetListener |
Adapter class | Listener interface |
---|---|
MouseInputAdapter | MouseInputListener |
InternalFrameAdapter | InternalFrameListener |
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
输出:
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
输出:
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter{
Frame f;
MouseMotionAdapterExample(){
f=new Frame("Mouse Motion Adapter");
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
输出:
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}
输出: