java上机实验
我们使用的教材是《java简明教程(第三版)》- 皮德常
使用Applet随机画线
找规律天下第一
今天偷懒一波,深夜发博就很开心。还是老样子,小板凳都放好了,准备听讲。
- 首先随机俩字就需要使用到
Math.Random
这个东西了。 - 然后颜色的话,我们使用
Color
类 - 最后循环的话,简简单单
暴力美学
import java.awt.*;
import java.applet.*;
public class screenSaver extends Applet{
private int windowWidth=800, windowHeight=600;
@Override
public void init() {
setSize(windowWidth,windowHeight);
}
@Override
public void paint(Graphics graphics) {
// set the screen
graphics.clearRect(0,0,windowWidth,windowHeight);
for (int i = 0; i < 100; i++) {
// drawing the Lines
drawRandomColorLines(graphics);
if(i == 99){
// reset and refresh
i = 0;
graphics.clearRect(0,0,windowWidth,windowHeight);
}
}
}
private void drawRandomColorLines(Graphics graphics) {
// setting a random color
int r, g, b;
r = (int)(Math.random() * 255);
g = (int)(Math.random() * 255);
b = (int)(Math.random() * 255);
Color color = new Color(r,g,b);
graphics.setColor(color);
// setting a random position
int x1, x2, y1, y2;
x1 = (int)(Math.random() * windowWidth);
y1 = (int)(Math.random() * windowHeight);
x2 = (int)(Math.random() * windowWidth);
y2 = (int)(Math.random() * windowHeight);
graphics.drawLine(x1,y1,x2,y2);
try{
Thread.sleep(100);// drawing speed
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
实验效果:
随谈
我使用init()
方法实现了调节默认窗口大小,方便我们看效果。
@Override
public void init() {
setSize(windowWidth,windowHeight);
}
对于刷新(清除)屏幕的话,我们只要调用clearRect(x1, y1, x2, y2)
此方法来用背景色填充指定范围(俩点之间的矩形)的窗口。一开始刷新一次,后进入循环每100下再调用方法就可以实现刷新屏幕了。
graphics.clearRect(0,0,windowWidth,windowHeight);
for (int i = 0; i < 100; i++) {
// drawing the Lines
drawRandomColorLines(graphics);
if(i == 99){
// reset and refresh
i = 0;
graphics.clearRect(0,0,windowWidth,windowHeight);
}
}
我们在上面建立随机的颜色时,以及随机的位置时,都用到了Math.Random
方法,这个方法会生成0-1之间的任意数,因为我们需要的是整数随意类型强制转换(int)
例如下面这样
int r, g, b;
r = (int)(Math.random() * 255);
g = (int)(Math.random() * 255);
b = (int)(Math.random() * 255);
Color color = new Color(r,g,b);
graphics.setColor(color);
serColor(Color c)
使用这个方法来设置当前的前景色,在画的时候就会以这个前景色来画画,同理:
int x1, x2, y1, y2;
x1 = (int)(Math.random() * windowWidth);
y1 = (int)(Math.random() * windowHeight);
x2 = (int)(Math.random() * windowWidth);
y2 = (int)(Math.random() * windowHeight);
graphics.drawLine(x1,y1,x2,y2);
drawLine(x1, y1, x2, y2)
使用这个方法画直线,需要俩个点的位置,例如(x1,y1)和(x2,y2)。传入方法后,画出两点之间的直线。
有一股隐形的不可抗拒的力量在我体内,我先去解决一下。
叨叨几句... NOTHING