1.定义监听器类的另一种方式e.getSource()来获得事件源
2.适配器
3.随着鼠标拖动而移动的字符串
public MoveMessagePanel(String message) {
this.message = message;
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, x, y);
}
}
4.鼠标事件
mousePressed,mouseReleased,mouseClicked,mouseEntered,mouseExited,mouseDragged,mouseMoved
注意:MouseMotionListener 处理拖动和移动,MouseListener处理鼠标键按下,释放,点击,进入和退出
5.键盘事件
keyPressed,keyReleased,keyTyped
getKeyChar()返回输入的字符,getKeyCode()返回按键常量表中的值VK....
注意:仅有一个焦点的组件能接收KeyEvent p.setFocusable(true);要记得设置!!!!
6.Timer类
Timer(int 延迟,listener 监听器) 构造
addActionListener();
start();
stop();
setDelay(int 延迟);
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class AnimationDemo extends JFrame {
public AnimationDemo(){
MovingMessagePanel p=new MovingMessagePanel("锄禾日当午,汗滴禾下土");
add(p);
setSize(500,300);
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new AnimationDemo();
}
static class MovingMessagePanel extends JPanel{
private String message="海上生明月,天涯共此时";
private int x=0;
private int y=20;
public MovingMessagePanel(String message){
this.message=message;
Timer timer=new Timer(1000, new TimerListener());
timer.start();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(x>getWidth()){
x=-20;
}
x+=5;
g.drawString(message, x, y);
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}
}
}
Timer timer=new Timer(1000,new TimerListener());
time监听器调用重画的方法
7.自己写Cell类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class NineCoins extends JFrame {
public NineCoins() {
setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++)
add(new ClickableCell("H"));
}
/** An inner class for displaying a cell */
static class ClickableCell extends JLabel {
public ClickableCell(String s) {
setBorder(new LineBorder(Color.black, 1)); // Cell border
setHorizontalAlignment(JLabel.CENTER);
setFont(new Font("TimesRoman", Font.BOLD, 20));
setText(s);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (getText().equals("H")) {
setText("T"); // Flip from H to T
}
else {
setText("H"); // Flip from T to H
}
}
});
}
}
/** This main method enables the applet to run as an application */
public static void main(String[] args) {
// Create a frame
JFrame frame = new NineCoins();
frame.setTitle("Exercise16_36");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}