在java中怎样使放有图片的label移向鼠标点击的坐标??
我想做一个由鼠标控制的小游戏,让label上的小图片移向鼠标点击的坐标。下面的代码我试了,不起作用finalJLabellabel=newJLabel(iconpx);l...
我想做一个由鼠标控制的小游戏,让label上的小图片移向鼠标点击的坐标。下面的代码我试了,不起作用
final JLabel label=new JLabel(iconpx);
label.setBounds(MouseX=300,MouseY=600,197,120);
pane.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
for(;(MouseX <=getX())&&(MouseY <=getY());){
if(MouseX <=getX()){
MouseX+=5;
repaint();
}
else{
MouseX-=5;
repaint();
}
if(MouseY <=getY()){
MouseY+=5;
repaint();
}
else{
MouseY-=5;
repaint();
}
try{
Thread.sleep(5000);
}catch(Exception e){}
}
} 展开
final JLabel label=new JLabel(iconpx);
label.setBounds(MouseX=300,MouseY=600,197,120);
pane.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
for(;(MouseX <=getX())&&(MouseY <=getY());){
if(MouseX <=getX()){
MouseX+=5;
repaint();
}
else{
MouseX-=5;
repaint();
}
if(MouseY <=getY()){
MouseY+=5;
repaint();
}
else{
MouseY-=5;
repaint();
}
try{
Thread.sleep(5000);
}catch(Exception e){}
}
} 展开
3个回答
2013-07-20
展开全部
我这里有标签随鼠标移动的代码,你复制下来看看:
import java.awt.*;
import java.awt.event.*;
public class LableTest extends Frame {
Label l;
Panel p;
int x=10,y=10;
public LableTest(){
super("标签走动的演示");
p=new Panel();
l=new Label("标签");
l.setBackground(Color.red);
l.setBounds(x,y,100,50);
p.add(l);
this.add("Center",p);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ex){
System.exit(0);
}});
p.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
x=e.getX();y=e.getY();
l.setLocation(x,y);
}});
this.setSize(400,400);
this.setVisible(true);
}
public static void main(String args[]){
new LableTest();
}
}
import java.awt.*;
import java.awt.event.*;
public class LableTest extends Frame {
Label l;
Panel p;
int x=10,y=10;
public LableTest(){
super("标签走动的演示");
p=new Panel();
l=new Label("标签");
l.setBackground(Color.red);
l.setBounds(x,y,100,50);
p.add(l);
this.add("Center",p);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ex){
System.exit(0);
}});
p.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
x=e.getX();y=e.getY();
l.setLocation(x,y);
}});
this.setSize(400,400);
this.setVisible(true);
}
public static void main(String args[]){
new LableTest();
}
}
2013-07-20
展开全部
你根本就没有用MouseEvent事件获取你鼠标的位置啊,还有getX()不能直接这么调用,你程序里的getX()是获取JFrame中JPanel的坐标而已,你应该用agr0.getX()(方法我不记得了,自己查一下api)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2013-07-20
展开全部
看不懂。你这代码太笼统,从这上面看完全搞不清,你这段代码里有N多未初始化的变量,还有那个侦听,实例化的很诡异 - -!有完整的代码没有?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询