|
/**
* 视图
*
* @author zangweiren 2010-4-12
*
*/
public class BallView implements Observer {
private BallController controller;
private Ball ballModel;
private JButton move;
private JButton stop;
private JButton speedUp;
private JButton slowDown;
private JFrame main = new JFrame();
private JPanel ballPanel;
private JButton ball;
private JLabel speed;
private boolean moving = false;
public BallView(BallController controller, Ball ballModel) {
this.controller = controller;
this.ballModel = ballModel;
this.ballModel.registerObserver(this);
initView();
showBall();
}
private void drawBall(int x, int y) {
ball.setLocation(x, y);
}
private void initView() {
main.setTitle("MVC Pattern");
main.setSize(300, 200);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setResizable(false);
move = new JButton("Move");
stop = new JButton("Stop");
speedUp = new JButton(">>");
slowDown = new JButton("<<");
ballPanel = new JPanel();
ball = new JButton();
ball.setBackground(Color.RED);
ball.setEnabled(false);
ball.setSize(20, 20);
ball.setLocation(0, 50);
JPanel p = new JPanel();
p.add(move);
p.add(slowDown);
p.add(speedUp);
p.add(stop);
stop.setEnabled(false);
speed = new JLabel("Current speed:" + ballModel.getSpeed());
JPanel speedPanel = new JPanel();
speedPanel.add(speed);
main.getContentPane().add(speedPanel, BorderLayout.NORTH);
ballPanel.add(ball);
main.getContentPane().add(ballPanel);
ballPanel.setLayout(null);
main.getContentPane().add(p, BorderLayout.SOUTH);
main.setVisible(true);
move.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.move();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.stop();
}
});
speedUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.speedUp();
}
});
slowDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.slowDown();
}
});
}
public void setMoveButtonEnable(boolean b) {
move.setEnabled(b);
}
public void setMoving(boolean b) {
this.moving = b;
}
public void setStopButtonEnable(boolean b) {
stop.setEnabled(b);
}
public void showBall() {
new Thread() {
@Override
public void run() {
int x = 0;
int y = 50;
while (true) {
if (!moving) {
continue;
}
drawBall(x, y);
try {
if (ballModel.getSpeed() != 0) {
Thread.sleep(1000 / ballModel.getSpeed());
x++;
if (x > 290) {
x = 0;
}
} else {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void speedChanged() {
speed.setText("Current speed:" + ballModel.getSpeed());
}
} |
|