一个小试验:
要求:
写一个程序,该程序启动后出现一个窗口,窗口上有一个按钮,按一下这个按钮,就在窗口中的随机位置产生一个随机颜色的方块,停留3秒后消失,每个方块均是一个线程产生
代码:
package base;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
static final int frame_width = 300;
static final int frame_hidth = 800;
final JFrame frame = new JFrame("测试");
JPanel panel = new JPanel();
public void startFrame() {
final JButton button = new JButton("点一下");
button.setSize(10, 10);
button.setForeground(Color.RED);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 清空Panel
panel.remove(button);
panel.repaint();
// 开始一个线程
ButtonThread t = new ButtonThread();
t.start();
}
});
panel.add(button);
frame.add(panel);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// button
Test test = new Test();
test.startFrame();
JFrame myframe = test.frame;
myframe.setSize(frame_hidth, frame_width);
myframe.setVisible(true);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ButtonThread extends Thread {
public void run() {
JPanel myPanel = panel;
// 清空
panel.removeAll();
JButton aButton = new JButton("好好学习,天天向上");
aButton.setSize(50, 50);
aButton.setLocation(getALocation_X(), getALocation_Y());// 变化位置
aButton.setBackground(getAColor());// 变化颜色
aButton.repaint();
panel.add(aButton);
myPanel.repaint();
frame.add(myPanel);
try {
sleep(3000);
new ButtonThread().start();
notify();
destroy();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 得到随机的一个颜色
public Color getAColor() {
int r, g, b;
Random rand = new Random();
r = rand.nextInt(255);
g = rand.nextInt(255);
b = rand.nextInt(255);
Color c = new Color(r, g, b);
return c;
}
// 得到随机的一个位置X
public int getALocation_X() {
Random rand = new Random();
return rand.nextInt(frame_width);
}
// 得到随机的一个位置Y
public int getALocation_Y() {
Random rand = new Random();
return rand.nextInt(frame_hidth);
}
}
}