【发布时间】:2014-06-06 06:21:13
【问题描述】:
不知道如何做到这一点让我很生气。我目前有一个带有球的框架,它沿对角线向下和向右移动,当它与框架的边缘碰撞时,它需要反弹。反弹部分我可以自己解决,我需要帮助的是球知道它何时撞击框架边缘。
主要:
class ControlledBall extends JPanel {
private int x = 70;
private int y = 30;
private boolean yes = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
Ellipse2D.Double ball = new Ellipse2D.Double(x,y,50,50);
g2.draw(ball);
g2.fill(ball);
}
public void moveRight(int d) {x = x + d;}
public void moveDown(int d) {y = y + d;}
public void gogo() {yes = true;}
public void nono() {yes = false;}
public static void main(String[] args) {
JFrame frame = new Viewer();
frame.setSize(500, 500);
frame.setTitle("Bouncing Ball");
frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
frame.setVisible(true);
}
}
查看器类:
public class Viewer extends JFrame {
JButton go = new JButton("GO");
JButton stop = new JButton("STOP");
JPanel buttons = new JPanel();
Timer timer;
ControlledBall cbPanel = new ControlledBall();
JPanel left = new JPanel();
JPanel right = new JPanel();
JPanel top = new JPanel();
class gogoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.gogo();
timer.start();
}
}
class nonoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.nono();
timer.stop();
}
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.moveRight(5);
cbPanel.moveDown(5);
repaint();
}
}
public Viewer() {
buttons.add(go);
buttons.add(stop);
this.add(buttons, BorderLayout.SOUTH);
this.add(cbPanel, BorderLayout.CENTER);
this.add(right, BorderLayout.EAST);
this.add(top, BorderLayout.NORTH);
this.add(left, BorderLayout.WEST);
timer = new Timer(50, new TimerListener());
go.addActionListener(new gogoListener());
stop.addActionListener(new nonoListener());
timer.start();
cbPanel.setBorder(BorderFactory.createLineBorder(Color.black));
}
}
【问题讨论】:
-
请参阅Collision detection with complex shapes 以获取工作示例。虽然无可否认,一个圆(球)和可显示区域(一个矩形)将使其开放给一个比 JRE 在我的示例中执行的更简单的公式。
标签: java swing jframe awt java-2d