Swing-滑鼠監聽-左鍵右鍵
阿新 • • 發佈:2018-12-02
大家好:
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(); } }