- 공놀이
1차 공튀기기
import java.awt.*;
import javax.swing.*;
public class DangguGO extends JApplet {
int x=30,y=0;
int xTurn=1,yTurn=1;
public void init(){
Drawing d = new Drawing();
getContentPane().add(d,null);
}
class Drawing extends Canvas{
public void paint(Graphics g){
this.setBackground(Color.GREEN);
g.setColor(Color.WHITE);
g.fillOval(x,y,30,30);
x+=xTurn;
y+=yTurn;
if(x>=getContentPane().getWidth()-30||x<=0){
xTurn*=-1;
}
if(y>=getContentPane().getHeight()-30||y<=0){
yTurn*=-1;
}
this.repaint();
try{Thread.sleep(10);}catch(Exception e){}
}
}
}
======================================================
공놀이 완성
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DangguGO extends JApplet implements ActionListener {
int x=1,y=1;
int xTurn=(int)(Math.random()*5+1),yTurn=(int)(Math.random()*5+1);
Button b =new Button("고고싱");
int gogo=1;
public void init(){
getContentPane().add(new Drawing(),BorderLayout.CENTER);
b.addActionListener(this);
getContentPane().add(b,BorderLayout.SOUTH);
}
public void actionPerformed (ActionEvent e){
if(e.getSource()==b){
gogo*=-1;
if(gogo==-1){//JOptionPane.showMessageDialog(this,"고고싱");
b.setLabel("스탑");
}
else{// JOptionPane.showMessageDialog(this,"스답");
b.setLabel("고고싱");
}
}
}
class Drawing extends Canvas{
Drawing(){
new Thread(){
public void run(){
while(true){
try{
x+=xTurn;
y+=yTurn;
while(gogo==1)Thread.sleep(5);
repaint();
Thread.sleep(10);
}catch(Exception e){}
}
}
}.start();
}
public void paint(Graphics g){
this.setBackground(Color.GREEN);
g.setColor(Color.WHITE);
//화면밖 도주금지
if(x<0){
x=0;
xTurn*=(-1);
}
if(y<0){
y=0;
yTurn*=(-1);
}
//그리기
g.fillOval(x,y,30,30);
//시네루 및 팅기기
if(x>=getContentPane().getWidth()-30||x<0){
xTurn=(int)(Math.random()*5);
xTurn*=-1;
}
if(y>=getContentPane().getHeight()-48||y<0){
yTurn=(int)(Math.random()*5);
yTurn*=-1;
}
try{Thread.sleep(10);}catch(Exception e){}
}
}
}

카테고리