
JButton button = new JButton("Move");
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
add(buttonPanel, BorderLayout.NORTH);
class MoveListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// behavior goes here
}
}
button.addActionListener(new MoveListener());
public void actionPerformed(ActionEvent event)
{
carComponent.updatePositions();
}
public void updatePositions()
{
for (Car car : cars) car.move(5, 0);
repaint();
}
repaint calls paintComponent, which draws
objects in new positionTimer t = new Timer(100, new MoveListener()); // 100 milliseconds between actions t.start();
Graphics2D
public class Dog
{
private int x;
private int y;
private Image image;
public Dog(int x, int y)
{
this.x = x;
this.y = y;
try
{
image = ImageIO.read(new File("dog.png"));
}
catch (IOException ex)
{
System.out.println("Can't read image.");
}
}
public void draw(Graphics2D g2)
{
g2.drawImage(image, x, y, null);
}
public void move(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
}
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
// behavior goes here
}
// Do-nothing methods
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
component.addMouseListener(new MousePressListener());
for (Car car : cars) if (car.contains(x, y)) /* Do something with car */
Car.contains to test that (x, y) falls inside the
carmove, turn etc. take time (default 1 sec.)DoTogether. Syntax
is icky:
DoTogether.invokeAndWait(
new Runnable() { public void run() { /* movement #1 */ } },
new Runnable() { public void run() { /* movement #2 */ } },
new Runnable() { public void run() { /* movement #3 */ } });
public Robot(int x, int y)
{
this.x = x;
this.y = y;
setLocalPointOfView(new PointOfView(
new Quaternion(0, 0, 0, 1), // orientation
new Position(x, -0.05, y))); // Alice x is left-right, y is bottom-top, z is front-back
}
final Car car = ...;
class ClickListener implements MouseButtonListener
{
public void mouseButtonClicked(MouseButtonEvent mbe)
{
car.say("Hello");
}
}
car.addMouseButtonListener(new ClickListener());