Below is my code. I'm new to java.swing and java.awt. Do I need to put in a new action listener as well as a mouseListener? Because the shape is moving I'm not exactly sure how to set this code up.
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;
}
Could you include the code for the MoveableShape and ShapeIcon? This makes it easier to run your code and see what it is doing.
If you want to change the direction of the car when it is clicked, you could add a mouse listener to the label that contains the car shaped icon:
The car should now change direction whenever you click on the label, which is the rectangle surrounding the car.
(In the example above, I've used a MouseAdapter which allows you to only implement the methods of the MouseListener interface that you need, the others do nothing.)