java鼠标各按键单击和左键击双击

下面代码实现了鼠标各按键单击和左键击双击,以及右键弹出菜单


JButton btn = new JButton("鼠标左键、右键、滚轮点击测试");
		btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1) {
					JOptionPane.showMessageDialog(MainFrame.this, "鼠标左键");
				} else if (e.getButton() == MouseEvent.BUTTON2) {
					JOptionPane.showMessageDialog(MainFrame.this, "鼠标滚轮点击");
				} else if (e.getButton() == MouseEvent.BUTTON3) {
					JOptionPane.showMessageDialog(MainFrame.this, "鼠标右键");
				}
				super.mousePressed(e);
			}
		});
		JButton btn2 = new JButton("鼠标单击双击测试");
		btn2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1
						&& e.getClickCount() == 2) {
					JOptionPane.showMessageDialog(MainFrame.this, "鼠标双击");
				}
				super.mousePressed(e);
			}
		});
		JButton btn3 = new JButton("右键弹出菜单");
		btn3.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent event) {
				// 调用triggerEvent方法处理事件
				//triggerEvent(event);
				// isPopupTrigger():返回此鼠标事件是否为该平台的弹出菜单触发事件。
				if (event.isPopupTrigger())
					// 显示菜单
					popupMenu.show(event.getComponent(), event.getX(), event.getY());
			}

			@Override
			public void mouseReleased(MouseEvent event) {
				//triggerEvent(event);
				// isPopupTrigger():返回此鼠标事件是否为该平台的弹出菜单触发事件。
				if (event.isPopupTrigger())
					// 显示菜单
					popupMenu.show(event.getComponent(), event.getX(), event.getY());
			}
		});


你可能感兴趣的:(java)