JACK_JYH的博客

努力,也是一种天赋

鼠标,键盘监听器(Java)

鼠标

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);
    }

}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JACK_JYH/article/details/52347286
文章标签: java 鼠标 键盘
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭