【发布时间】:2014-01-18 08:31:36
【问题描述】:
我正在尝试编写一个关于弹跳球的代码,但我不知道如何让球弹跳。代码似乎是正确的,没有来自 eclipse 的错误消息,但球没有移动。感谢任何帮助/提示。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BouncingBallTest extends JFrame {
private JButton jbtStart = new JButton("Start");
private JButton jbtStop = new JButton("Stop");
private Ball canvas = new Ball();
public BouncingBallTest() {
JPanel panel = new JPanel(); // Use the panel to group buttons
panel.add(jbtStart);
panel.add(jbtStop);
add(canvas, BorderLayout.CENTER); // Add canvas to centre
add(panel, BorderLayout.SOUTH); // Add panel to south
// register listener
jbtStart.addActionListener(new StartBouncingBallTest());
jbtStop.addActionListener(new StopBouncingBallTest());
}
// the main method
public static void main(String[] args) {
JFrame frame = new BouncingBallTest();
frame.setTitle("Bouncing Ball Test");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(470, 300);
frame.setVisible(true);
}
class StartBouncingBallTest implements ActionListener { // inner class
@Override
public void actionPerformed(ActionEvent e) {
canvas.StartBouncingBallTest();
}
}
class StopBouncingBallTest implements ActionListener { // inner class
@Override
public void actionPerformed(ActionEvent e) {
canvas.StopBouncingBallTest();
}
}
class Ball extends JPanel {
private int radius = 10;
private int x;
private int y;
private int dx = 3;
private int dy = 3;
private Timer timer = new Timer(20, new TimerListener());
public void StartBouncingBallTest() {
if (x > 0 && y > 0) {
x += dx;
y += dy;
}
else if (x == 0) {
x -= dx;
y += dy;
}
else if (y + (2 * radius) > getHeight()) {
x += dx;
y -= dy;
}
else if (y == 0) {
x += dx;
y -= dy;
}
else if (x + (2 * radius) > getWidth()) {
x -= dx;
y += dy;
}
repaint();
timer.start();
}
public void StopBouncingBallTest() {
timer.stop();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval(x, y, 2 * radius, 2 * radius);
}
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}
【问题讨论】:
-
您的计时器操作根本不会修改坐标。将定位代码移到那里,您应该会看到一些移动。
-
我试过了,但没有任何反应..
标签: java swing events user-interface actionlistener