Swing-鼠标监听-左键右键

大家好:

Swing中鼠标监听事件:左键减一,右键加一。

package com.zyx.cn.baidu_test.day1;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
 * java.awt一个点赞按钮如何实现右键加1左键减1
 * @author yltd
 *
 */
public class FrameZuoYouJian extends JFrame{
	private static final long serialVersionUID = 1L;
	//主页
	public static void home(){
		JFrame jFrame =new JFrame("示例");
		JButton jButton =new JButton("点赞");
		jButton.setSize(100, 100);
		JTextField text =new JTextField();
		text.setSize(100, 100);
		// 加入mouse监听
		jButton.addMouseListener(new MouseListener() {
			int number =0;
			@Override
			public void mouseReleased(MouseEvent e) {// 鼠标松开
			}
			@Override
			public void mousePressed(MouseEvent e) {// 鼠标按下
			}
			
			@Override
			public void mouseExited(MouseEvent e) {// 鼠标退出组件
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {// 鼠标进入组件
			}
			@Override
			public void mouseClicked(MouseEvent e) {// 鼠标单击事件
				int c = e.getButton();// 得到按下的鼠标键
				if (c == MouseEvent.BUTTON1){ // 判断是鼠标左键按下
					number--;
					text.setText(number+"");
				}
				if (c == MouseEvent.BUTTON3) {// 判断是鼠标右键按下
					number++;
					text.setText(number+"");
				}
			}
		});
		jFrame.add(jButton);
		jFrame.add(text);
		jFrame.setVisible(true);
		jFrame.setSize(400, 400);
		jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	//主入口
	public static void main(String[] args) {
		home();
	}
}

Swing-鼠标监听-左键右键_第1张图片

你可能感兴趣的:(Swing)