java中JFrame的鼠标移动事件相关问题
我写了下面这一段有关小球的代码,不知道为啥鼠标事件没有反应,鼠标拖不动小球。importjava.awt.*;importjava.awt.event.*;importj...
我写了下面这一段有关小球的代码,不知道为啥鼠标事件没有反应,鼠标拖不动小球。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPractice extends JFrame implements MouseMotionListener{
int x=100,y=100;
public MyPractice(){
setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
//初始化小球
g.fillOval(x, y, 30, 30);
}
public static void main(String args[]){
new MyPractice();
}
//鼠标移动事件
@Override
public void mouseDragged(MouseEvent e) {
x=e.getX();
y=e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
} 展开
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPractice extends JFrame implements MouseMotionListener{
int x=100,y=100;
public MyPractice(){
setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
//初始化小球
g.fillOval(x, y, 30, 30);
}
public static void main(String args[]){
new MyPractice();
}
//鼠标移动事件
@Override
public void mouseDragged(MouseEvent e) {
x=e.getX();
y=e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
} 展开
1个回答
展开全部
你可以这样改
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPractice extends JFrame {
int x=100,y=100;
public MyPractice(){
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
x=e.getX();
y=e.getY();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
});
setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
//初始化小球
g.fillOval(x, y, 30, 30);
}
public static void main(String args[]){
new MyPractice();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPractice extends JFrame {
int x=100,y=100;
public MyPractice(){
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
x=e.getX();
y=e.getY();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
});
setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
//初始化小球
g.fillOval(x, y, 30, 30);
}
public static void main(String args[]){
new MyPractice();
}
}
追问
这样改确实可以动了。可是小球移动时会闪烁,有办法可以解决吗?是因为没有用到JPanel的原因么
追答
我给你私信了另外一种改法了
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询