java中窗体上有一个Button和一个TextArea当鼠标经过按钮上的某一点时在文本框中输出该点的坐标事件
你好!只需要在按钮上添加鼠标监听器监听鼠标经过事件就可以了
核心代码:
private void btnMouseMoved(java.awt.event.MouseEvent evt) {
textArea.append("当前鼠标经过"+evt.toString()+'\n');
textArea.append("当前鼠标经过"+evt.getPoint().toString()+'\n');
}
完整实例:
/*
* TestMouseCross.java
*
* Created on 2011-5-8, 11:56:21
*/
package test;
/**
*
* @author 叶科良
*/
public class TestMouseCross extends javax.swing.JFrame {
/** Creates new form TestMouseCross */
public TestMouseCross() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("点击获取坐标事件");
btn.setText("经过获取坐标事件及位置");
btn.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
btnMouseMoved(evt);
}
});
textArea.setColumns(15);
textArea.setRows(5);
jScrollPane1.setViewportView(textArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(btn)
.addContainerGap(107, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(btn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnMouseMoved(java.awt.event.MouseEvent evt) {
textArea.append("当前鼠标经过"+evt.toString()+'\n');
textArea.append("当前鼠标经过"+evt.getPoint().toString()+'\n');
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestMouseCross().setVisible(true);
}
});
}
// Variables declaration - do not modify
protected javax.swing.JButton btn;
protected javax.swing.JScrollPane jScrollPane1;
protected javax.swing.JTextArea textArea;
// End of variables declaration
}