我用Java制作了一个弹跳球,但现在我必须在动画中添加“开始”和“停止”按钮,但我不确定如何去做。 这就是我到目前为止所做的:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//import javax.swing.JFrame;
//import javax.swing.JPanel;
//import javax.swing.Timer;
/**
*
*
*/
public class BouncingBall extends JPanel implements ActionListener {
Timer tm = new Timer(5,this);
int x = 0, velX = 1;
int y = 0, velY = 1;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.yellow);
g.fillOval(x, y, 50, 50);
tm.start();
}
public void actionPerformed(ActionEvent E)
{
if(x < 0 || x > 550)
velX = -velX;
if (y < 0 || y > 280)
velY = -velY;
x = x + velX;
y = y + velY;
repaint();
}
public static void main(String[] args) {
BouncingBall s = new BouncingBall();
JFrame jf = new JFrame();
jf.setTitle("Bouncing Ball");
jf.setSize(600,350);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
}
}
关于如何实现启动/停止按钮的任何想法?
提前谢谢
更新: 我做了以下,但由于这一行,我收到了一个错误: start.addActionListener(本); 它说“非静态变量,这不能从静态上下文引用”
public void actionPerformed(ActionEvent E)
{
if (E.getActionCommand().equals("Start")){
if(x < 0 || x > 550)
velX = -velX;
if (y < 0 || y > 280)
velY = -velY;
x = x + velX;
y = y + velY;
repaint();
}
else
{}
}
public static void main(String[] args) {
BouncingBall s = new BouncingBall();
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JButton start = new JButton("Start");
start.addActionListener(this);
jp.add(start);
jf.add(jp,BorderLayout.SOUTH);
jf.setTitle("Bouncing Ball");
jf.setSize(600,350);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
}
}
谁能告诉我我做错了什么?重复的问题对我没什么帮助。