希望各位大侠帮忙写一下下面这个鼠标事件的java代码
主要是mouseMoved和mouseDragged这两个方法 ,非常感谢~~~~~
完成界面并实现功能:
(1)当鼠标在窗口上移动时,按钮跟着一起移动
(2)当按下鼠标在窗口上移动时(即拖拉),在按钮上显示鼠标的位置
------解决方案--------------------
package w.j.AWT;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Wannabes extends JFrame {
JPanel jPanel;
JButton jButton;
public Wannabes() {
jPanel = new JPanel();
jButton = new JButton("别想甩掉我");
this.jButton.setBounds(50, 70, 100, 30);
jButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
jButton.setText(x + " : " + y);
}
});
jPanel.setLayout(null);
jPanel.add(jButton);
jPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
jButton.setBounds(x, y, 100, 30);
}
});
this.add(jPanel);
this.setTitle("我是跟屁虫。 哥们,你看这么写的行么?");
this.setSize(400, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
Wannabes wann = new Wannabes();
}
}
------解决方案--------------------
兄弟,监听器搞错了,应该是mouseMoved,不是mouseDragged
我改了下,还行,版权是二楼的
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test1 extends JFrame {
JPanel jPanel;
JButton jButton;
public test1() {
jPanel = new JPanel();
jButton = new JButton("别想甩掉我");
this.jButton.setBounds(50, 70, 100, 30);
jButton.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
jButton.setText(x + " : " + y);
}
});
jPanel.setLayout(null);
jPanel.add(jButton);
jPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
jButton.setBounds(x, y, 100, 30);}
});
this.add(jPanel);