package class9_Lab_MapperPersonWriter; import javax.swing.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.Serializable; import java.util.Random; /** * Extending JLabel may not be the best way to do this... */ public class Person implements Serializable { private static final ImageIcon NORMAL_ICON = new ImageIcon(Person.class.getResource("smiley.png")); private static final ImageIcon SCARED_ICON = new ImageIcon(Person.class.getResource("scared.png")); private static final Random GENERATOR = new Random(); private final JLabel displayOfMe; private int person2; private int x; private int y; /** * Create a person in the top-right corner of the image. */ public Person() { displayOfMe = new JLabel(NORMAL_ICON); displayOfMe.setBounds(0, 0, displayOfMe.getPreferredSize().width, displayOfMe.getPreferredSize().height); displayOfMe.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { displayOfMe.setIcon(SCARED_ICON); } @Override public void mouseExited(MouseEvent e) { displayOfMe.setIcon(NORMAL_ICON); } }); } /** * Get the JLabel used to display me * @return the JLabel */ public JLabel getDisplayOfMe() { return displayOfMe; } /** * Move the person to a new location. * The position given is the CENTER of the person. * * @param x horizontal position in pixels from top left * @param y vertical position in pixels from top left */ public void setPosition(int x, int y) { this.x = x; this.y = y; displayOfMe.setLocation(x- displayOfMe.getPreferredSize().width/2, y- displayOfMe.getPreferredSize().height/2); } /** * Move the person to a new location. * The position given is the CENTER of the person. * * @param deltaX change in horizontal position in pixels. Positive: move right, negative: move left. * @param deltaY change in vertical position in pixels. Positive: moved down, negative: move up */ public void moveBy(int deltaX, int deltaY) { this.x += deltaX; this.y += deltaY; displayOfMe.setLocation(x- displayOfMe.getPreferredSize().width/2, y- displayOfMe.getPreferredSize().height/2); } /** * * @param maxX maximum position in the X direction * @param maxY maximum position in the Y direction */ public void jump(int maxX, int maxY){ setPosition(GENERATOR.nextInt(maxX), GENERATOR.nextInt(maxY)); } }