我在计时器中移动 JLabel,但它朝错误的方向移动
I am moving a JLabel in a timer, but it is moving in the wrong direction
在 actionListener
for a JButton
on a JFrame
中,下面是对这个方法的调用。当victim==playerTwo
时,它正确。但是,当victim==playerOne
时,JLabel
图片的方向错了。在第一个场景中,JLabel
应该向右移动,在第二个场景中向左移动。如果您有任何问题,请告诉我,感谢您提供的任何帮助。
if(victim==playerTwo)
{
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(pic.getLocationOnScreen().x>1300)
{
((Timer)evt.getSource()).stop();
}
pic.setIcon(icon);
pic.setLocation((pic.getLocationOnScreen().x+5),45);
}
};
new Timer(delay, taskPerformer).start();
}
else
{
pic.setLocation(1000,500);
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(pic.getLocationOnScreen().x<0)
{
((Timer)evt.getSource()).stop();
}
pic.setIcon(icon);
pic.setLocation(((pic.getLocationOnScreen().x)-5),500);
}
};
new Timer(delay, taskPerformer).start();
}
您似乎混淆了 getLocation
and getLocationOnScreen
的用法
getLocation
使用相对于 父组件的坐标
getLocationOnScreen
使用相对于 屏幕的坐标
在屏幕上移动您的应用程序时,这种问题会变得更加明显。
更改您的代码以坚持父坐标系应该可以解决此问题:
pic.setLocation(((pic.getLocation().x)-5),500); // or +5 for player2
在 actionListener
for a JButton
on a JFrame
中,下面是对这个方法的调用。当victim==playerTwo
时,它正确。但是,当victim==playerOne
时,JLabel
图片的方向错了。在第一个场景中,JLabel
应该向右移动,在第二个场景中向左移动。如果您有任何问题,请告诉我,感谢您提供的任何帮助。
if(victim==playerTwo)
{
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(pic.getLocationOnScreen().x>1300)
{
((Timer)evt.getSource()).stop();
}
pic.setIcon(icon);
pic.setLocation((pic.getLocationOnScreen().x+5),45);
}
};
new Timer(delay, taskPerformer).start();
}
else
{
pic.setLocation(1000,500);
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(pic.getLocationOnScreen().x<0)
{
((Timer)evt.getSource()).stop();
}
pic.setIcon(icon);
pic.setLocation(((pic.getLocationOnScreen().x)-5),500);
}
};
new Timer(delay, taskPerformer).start();
}
您似乎混淆了 getLocation
and getLocationOnScreen
getLocation
使用相对于 父组件的坐标getLocationOnScreen
使用相对于 屏幕的坐标
在屏幕上移动您的应用程序时,这种问题会变得更加明显。
更改您的代码以坚持父坐标系应该可以解决此问题:
pic.setLocation(((pic.getLocation().x)-5),500); // or +5 for player2