📄 bouncezhuan.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
/**
Shows an animated bouncing ball running in a separate thread
*/
public class Bouncezhuan
{
public static void main(String[] args)
{
BounceFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class BounceFrame extends JFrame
{
public BounceFrame()
{
setSize(WIDTH, HEIGHT);
setTitle("BounceThread");
Container contentPane = getContentPane();
ButtonPanel buttonPanel = new ButtonPanel();
contentPane.add(buttonPanel);
}
public static final int WIDTH = 450;
public static final int HEIGHT = 350;
}
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
JButton star=new JButton("加球");
add(star);
//匿名内部类的实现
star.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
add();
}
});
JButton st=new JButton("减球");
add(st);
st.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
delet();
}
});
JButton sta=new JButton("开始");
add(sta);
sta.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
BallThread thread = new BallThread();
thread.start();
}
});
JButton end=new JButton("退出");
add(end);
end.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
});
}
//加球实践
public int add()
{ n=n+1;
return n;
}
//减球事件
public int delet()
{ n=n-1;
return n;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i <n; i++)
{
g2.fill(new Ellipse2D.Double(300+m*Math.sin((360*i/n+c)*Math.PI/180),
300+m*Math.cos((360*i/n+c)*Math.PI/180), 15, 15));
g2.setPaint(new Color((5*i+200)%360,10,(10*i)%360));
repaint();
}
}
//实现内部类
private class BallThread extends Thread
{
public BallThread(){}
public void run()
{
try
{
while(true)
{
m=(m+10)%150;
c=(c+20)%200;
sleep(200);
repaint();
}
}
catch (InterruptedException exception)
{
}
}
}
private int m;//run()方法调用时,球的半径的直。
private int n;//小球的个数
private int c;//run()方法调用时,球的旋转角度。
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -