本文主要是介绍弹跳的小球(applet实例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
直接上代码
功能:就是弹跳的小球碰到窗口的四个边边就会反向反弹,并提供停止,开始,和调整速度的三个控件。
Ball类是定义一些基本属性,包括初始化球的状态和球运动反弹的定义,和三个控件的方法。
package applet;import javax.swing.Timer;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;public class Ball extends JPanel{private int delay=10; //初始化速度private Timer timer=new Timer(delay,new TimerListener());private int x=0;private int y=0;private int radius=5;private int dx=2;private int dy=2;public Ball() {timer.start();}private class TimerListener implements ActionListener{public void actionPerformed(ActionEvent e) {repaint();}}public void paintComponent(Graphics g) {super.paintComponent(g);g.setColor(Color.red);if(x<radius) //这四个是边界dx=Math.abs(dx);if(x>getWidth()-radius)dx=-Math.abs(dx);if(y<radius)dy=Math.abs(dy);if(y>getHeight()-radius)dy=-Math.abs(dy);x+=dx; //下一次的位置是(x+dx,y+dy)y+=dy;g.fillOval(x-radius,y-radius,radius*2,radius*2);}public void suspend(){ //suspend和resume可以控制定时器的启动和停止timer.stop();}public void resume() {timer.start();}public void setDelay(int delay) {this.delay=delay;timer.setDelay(delay);}}
这个类就是把面板给搞出来,可视化的呈现出来,然后再把几个动作的监听器写了
package applet;import javax.swing.*;
import java.awt.event.*;
import java.awt.*;public class BallControl extends JPanel{private Ball ball=new Ball();private JButton jbtSuspend=new JButton ("Suspend");private JButton jbtResume=new JButton("Resume");private JScrollBar jsbDelay=new JScrollBar(); //滚动条public BallControl() {JPanel panel=new JPanel();panel.add(jbtSuspend);panel.add(jbtResume);ball.setBorder(new javax.swing.border.LineBorder(Color.red));jsbDelay.setOrientation(JScrollBar.HORIZONTAL);ball.setDelay(jsbDelay.getMaximum());setLayout(new BorderLayout());add(jsbDelay,BorderLayout.NORTH);add(ball,BorderLayout.CENTER);add(panel,BorderLayout.SOUTH);jbtSuspend.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {ball.suspend();}});jbtResume.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {ball.resume();}});jsbDelay.addAdjustmentListener(new AdjustmentListener() { //根据进度条调整速度public void adjustmentValueChanged(AdjustmentEvent e) {ball.setDelay(jsbDelay.getMaximum()-e.getValue());}});}
}
applet准备运行
package applet;import java.awt.*;
import javax.swing.*;public class BounceBallApp extends JApplet{public BounceBallApp() {add(new BallControl());}}
不知道为什么我的dos下面运行不了Appletviewer…直接点开html也 不行…
这篇关于弹跳的小球(applet实例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!