Java 在单击鼠标时,我应该在主方法中的何处放置新的mouseListener来设置CarShape left或right的动画?
下面是我的代码。我不熟悉java.swing和java.awt。我需要加入一个新的动作监听器和鼠标监听器吗?因为形状在移动,我不确定如何设置此代码Java 在单击鼠标时,我应该在主方法中的何处放置新的mouseListener来设置CarShape left或right的动画?,java,swing,animation,awt,mouse-listeners,Java,Swing,Animation,Awt,Mouse Listeners,下面是我的代码。我不熟悉java.swing和java.awt。我需要加入一个新的动作监听器和鼠标监听器吗?因为形状在移动,我不确定如何设置此代码 public class Animation { private static boolean goingRight = true; private static int posRight; public static void main(String[] args) { JFrame frame = ne
public class Animation {
private static boolean goingRight = true;
private static int posRight;
public static void main(String[] args) {
JFrame frame = new JFrame();
final MoveableShape shape = new CarShape(0, 0, CAR_WIDTH);
ShapeIcon icon = new ShapeIcon(shape, ICON_WIDTH, ICON_HEIGHT);
final JLabel label = new JLabel(icon);
frame.setLayout(new FlowLayout());
frame.add(label);
frame.pack();
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (posRight <= 0) {
goingRight = true;
}
if (posRight >= 300) {
goingRight = false;
}
if (goingRight) {
shape.translate(1, 0);
label.repaint();
posRight += 1;
} else {
shape.translate(-1, 0);
label.repaint();
posRight -= 1;
}
}
};
final int DELAY = 100;
Timer time = new Timer(DELAY, taskPerformer);
time.start();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final int ICON_WIDTH = 400;
private static final int ICON_HEIGHT = 100;
private static final int CAR_WIDTH = 100;
}
公共类动画{
私有静态布尔goingRight=true;
私权;
公共静态void main(字符串[]args){
JFrame=新JFrame();
最终可移动形状=新的车形(0,0,车宽);
形状图标=新的形状图标(形状、图标宽度、图标高度);
最终JLabel标签=新JLabel(图标);
frame.setLayout(新的FlowLayout());
框架。添加(标签);
frame.pack();
ActionListener taskPerformer=新建ActionListener(){
已执行的公共无效操作(操作事件){
if(posRight=300){
正确=错误;
}
如果(向右){
shape.translate(1,0);
label.repaint();
posRight+=1;
}否则{
shape.translate(-1,0);
label.repaint();
posRight-=1;
}
}
};
最终整数延迟=100;
计时器时间=新计时器(延迟、任务执行者);
time.start();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
私有静态最终整数图标\u宽度=400;
专用静态最终整型图标高度=100;
专用静态最终整备车宽度=100;
}
您能提供可移动形状和形状图标的代码吗?这样可以更容易地运行代码并查看它在做什么
如果要在单击汽车时更改其方向,可以向包含汽车形状图标的标签添加鼠标侦听器:
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
// Change the direction here...
}
});
现在只要你点击标签,汽车就会改变方向,标签是围绕汽车的矩形
(在上面的例子中,我使用了一个MouseAdapter,它只允许你实现你需要的MouseStener接口的方法,其他人什么都不做。)1重要的是要向我们解释你的想法,你想如何使用mouseevent制作动画,例如ShapeIcon将跟随鼠标光标,等等2。ActionListener中的if语句是错误的。3.label.revalidate();在label.repaint()之前;谢谢你的回复。该代码目前有效。汽车向右移动直到x=300,然后减去1直到x=0。我想修改我现有的主要方法,以改变方向,如果鼠标是在车内点击形状。我真的不需要保留检查方向和加减的当前代码。如果在CarShape内单击鼠标,我想修改现有的主方法以更改方向。==你在这里发布的代码中没有任何内容:-),那么…我不确定我是否理解你的评论。你想让我重申一下这个问题吗?