关闭

鼠标,键盘监听器(Java)

标签: java鼠标键盘
146人阅读 评论(0) 收藏 举报
分类:

鼠标

package jyh;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;
public class MouseEventDemo extends JFrame {
    JLabel label=new JLabel("");
    public MouseEventDemo(){
        setBounds(400,400,300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent event){
                label.setText("鼠标在"+event.getX()+","+getY()+"进行了单击");
            }
        });
        this.addMouseMotionListener(new MouseAdapter(){
            public void mouseMoved(MouseEvent event){
                label.setText("鼠标移动到了"+event.getX()+","+event.getY());
            }
        });
        setLayout(new BorderLayout());
        add(label,BorderLayout.CENTER);
    }
    public static void main(String[] args) {
        MouseEventDemo frame=new MouseEventDemo();
        frame.setVisible(true);
    }

}

键盘

package jyh;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class KeyEventDemo extends JFrame{
    JLabel label=new JLabel("按下了按钮:");
    public KeyEventDemo()
    {
        setSize(300,300);
        setLocation(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent event){
                switch(event.getKeyCode())
                {
                case KeyEvent.VK_UP:
                    label.setText("按下了按钮:UP");
                    break;
                case KeyEvent.VK_DOWN:
                    label.setText("按下了按钮:DOWN");
                    break;
                case KeyEvent.VK_LEFT:
                    label.setText("按下了按钮:LEFT");
                    break;
                case KeyEvent.VK_RIGHT:
                    label.setText("按下了按钮:RIGHT");
                    break;
                default:
                    label.setText("按下了按钮:"+event.getKeyChar());
                }
            }
        });
        setLayout(new BorderLayout());
        add(label,BorderLayout.CENTER);
    }
    public static void main(String[] args)
    {
        KeyEventDemo frame=new KeyEventDemo();
        frame.setVisible(true);
    }

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:74466次
    • 积分:3155
    • 等级:
    • 排名:第11309名
    • 原创:248篇
    • 转载:0篇
    • 译文:0篇
    • 评论:14条
    最新评论