⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mouseeventdemo.java

📁 Java 程序设计源码 只提供了部分
💻 JAVA
字号:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.event.MouseListener;
import java.awt.GridBagConstraints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class MouseEventDemo extends JFrame
	implements MouseListener,MouseMotionListener {
	String strPosition,strAction;
	DisplayPanel panel = new DisplayPanel();

	public MouseEventDemo() {
		super("鼠标事件");
		this.setSize(260,200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		addMouseListener(this);
		addMouseMotionListener(this);
		this.getContentPane().add(panel);
		panel.init();
	}

	public static void main(String[] args) {
		MouseEventDemo med = new MouseEventDemo();

		med.setVisible(true);
	}

	//接口实现
	public void mouseClicked(MouseEvent e) {
		strAction = "单击鼠标";

		panel.jtfAction.setText(strAction);
	}

	public void mousePressed(MouseEvent e) {
		strAction = "按下鼠标";

		panel.jtfAction.setText(strAction);
	}

	public void mouseReleased(MouseEvent e) {
		strAction = "松开鼠标";

		panel.jtfAction.setText(strAction);
	}

	public void mouseEntered(MouseEvent e) {
		strAction = "进入窗口";

		panel.jtfAction.setText(strAction);
	}

	public void mouseExited(MouseEvent e) {
		strAction = "退出窗口";

		panel.jtfAction.setText(strAction);
	}

	public void mouseDragged(MouseEvent e) {
		//空实现
	}

	public void mouseMoved(MouseEvent e) {
		strPosition = "X坐标:" + e.getX();
		strPosition +="Y坐标:" + e.getY();
	
		panel.jtfPosition.setText(strPosition);
	}
}

class DisplayPanel extends JPanel {
	JLabel jlbPosition, jlbAction;
	JTextField jtfPosition, jtfAction;

	//管理器对象
	GridBagLayout layout;
	GridBagConstraints con;

	//面板的初始化
	public void init() {
		layout = new GridBagLayout();
		con = new GridBagConstraints();

		this.setLayout(layout);
		jlbPosition = new JLabel("鼠标位置");
		jlbAction = new JLabel("鼠标动作");

		jtfPosition = new JTextField();
		jtfAction = new JTextField();

		con.anchor = GridBagConstraints.CENTER;
		con.fill = GridBagConstraints.HORIZONTAL;

		//添加组件到面板
		addComponent(this,layout,con,jlbPosition,0,0,1,1,20,0);
		addComponent(this,layout,con,jlbAction,1,0,1,1,20,0);
		addComponent(this,layout,con,jtfPosition,0,1,1,1,80,100);
		addComponent(this,layout,con,jtfAction,1,1,1,1,80,100);
	}

	private void addComponent(JPanel panel, GridBagLayout layout, GridBagConstraints gbc,
		Component com, int row, int column, int numRows, int numColumns, int Weightx, int Weighty) {
		gbc.gridx = row;
		gbc.gridx = column;
		gbc.gridwidth = numRows;
		gbc.gridheight = numColumns;
		gbc.weightx = Weightx;
		gbc.weighty = Weighty;
	
		layout.setConstraints(com,con);
		panel.add(com);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -