Java 鼠标点击事件实例

首先我们应该知道鼠标点击事件怎么实现

其部分代码如下

if (anyEvent.getButton() == MouseEvent.BUTTON1) {}
e.getButton()返回值分别为NOBUTTON、BUTTON1、BUTTON2、BUTTON3,分别代表着无点击、左击、中间键、右击三种情况

		<span style="font-family:Verdana;">事件源</span>.addMouseListener(new MouseAdapter() {//建立事件处理机制
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getButton()==e.BUTTON1){//点击鼠标左键
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是左键,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);
				}else if(e.getButton()==e.BUTTON2){//点击鼠标滑轮
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是滑轮,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);	
				}
				else if(e.getButton()==e.BUTTON3){//点击鼠标右键
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是右键,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);		
				}
			}
		});

具体实例,原题是《Java基础入门》

package BookProblem;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class P381Problem6A extends JFrame {
	private JPanel contentPane;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					P381Problem6A frame = new P381Problem6A();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * Create the frame.
	 */
	public P381Problem6A() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();

		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		JLabel label = new JLabel("此处显示鼠标右键点击的坐标");
		label.setBounds(5, 5, 424, 31);
		label.setOpaque(true);//设置控件不透明
		label.setBackground(Color.GREEN); //<span style="font-family:Verdana;">设置标间颜色</span>
		contentPane.add(label);
		contentPane.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getButton()==e.BUTTON1){
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是左键,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);
				}else if(e.getButton()==e.BUTTON2){
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是滑轮,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);	
				}
				else if(e.getButton()==e.BUTTON3){
					int x=e.getX();
					int y=e.getY();
					String str="您点击的是右键,鼠标当前点击位置的坐标是(" + x + "," + y+")";
					label.setText(str);		
				}
			}
		});
	}
}

效果图



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

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

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