JAVA 十 线程和异常处理
一个关于星星视图**
import java.awt.*;//awt调用视图类包
public class Draw {
public static void main(String[] args){
Frame w = new Frame();
w.setSize(1366, 768);
w.setBackground(Color.BLACK);
w.setVisible(true);
MyPanel mp = new MyPanel();
w.add(mp);
System.out.print((int)(Math.random()*1366));
}
}
class MyPanel extends Panel{
public void paint(Graphics g){
g.setColor(Color.WHITE);
for(int i=0;i<300;i++){
g.drawString("*",(int)(Math.random()*1366),(int)(Math.random()*768));
}
}
}
不要在一个package中建立很多很多类
//一个圆
import java.awt.*;
public class Ball {
public static void main(String[] args){
Frame w = new Frame();
w.setSize(1366,768);
w.setBackground(Color.BLACK);
w.setVisible(true);
MyPanel mp = new MyPanel();
w.add(mp);
}
}
class MyPanel extends Panel{
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillOval(400, 400, 20, 20);
}
}
线程:利用cpu轮转,实现多线程
implements实现
异常处理
try{
Thread.sleep(5);
}catch(Exception e){
}
//小球下降
import java.awt.*;
public class Ball {
public static void main(String[] args){
Frame w = new Frame();
w.setSize(1366,768);
w.setBackground(Color.BLACK);
w.setVisible(true);
MyPanel mp = new MyPanel();
w.add(mp);
Thread t=new Thread(mp);
t.start();
}
} //实现 线程接口
class MyPanel extends Panel implements Runnable{
int y=200;
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillOval(400, y, 20, 20);
}
@Override//编译器自动生成
public void run() {
// TODO Auto-generated method stub
while( true ){
y++;
if(y>768){
y=0;
}
try{
Thread.sleep(5);
}catch(Exception e){
}
repaint();
}
}
}