iT邦幫忙

0

JAVA繪圖及執行緒問題

各位大神好:
小弟想做一個讓人物去躲避彈跳球的遊戲,
現在球已經做好了,但是圖形會閃爍,
人物想先用一個矩形來代替,但是一直沒辦法出現,
自己的想法是新增一個執行緒繪出矩形及操控。
不知道是哪邊出了問題,希望各位大神能幫幫忙QQ

程式碼如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Attack_on_Ball extends JFrame implements ActionListener{
    static Attack_on_Ball frm = new Attack_on_Ball();
    static Button btn = new Button("Start");
    boolean clicked = false;
    CBall cb = new CBall();
    class CBall implements Runnable{ //球
        int x=(int)(Math.random()*800);
        int y=(int)(Math.random()*600);
        int movx=1;
        int movy=1;
        public void run(){
            clicked = true;
            Graphics g =getGraphics();
            try {
                while (true) {
                    paint(g);
                    moveBall();
                    Thread.sleep(10);
                    update(g);
                    moveBall();
                    Thread.sleep(10);
                }
            }catch(Exception ex){
                System.out.println(ex);
            }
        }
        public void moveBall(){ //球的移動
            if(x+movx > getWidth()-60)
                movx=-1;
            if(x+movx<0)
                movx=1;
            if(y+movy > getHeight()-60)
                movy=-1;
            if(y+movy<0)
                movy=1;
            x+=movx;
            y+=movy;
        }
        public void paint(Graphics g){ //球的繪圖
            if(clicked) {
                g.setColor(Color.gray);
                g.fillOval(x, y, 60, 60);
            }
        }

    }

    public static void main(String[] args){
        frm.setTitle("Attack on Ball");
        frm.setSize(800,600);
        frm.setLayout(null);
        btn.setBounds(700,40,100,40);
        frm.add(btn);
        btn.addActionListener(frm);
        frm.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){ //按下按鈕新增球和人物
        Character cha = new Character();
        Thread tc = new Thread(cha);
        tc.start();
        frm.addKeyListener(cha);
        CBall[] B = new CBall[5];
        Thread[] t = new Thread[5];
        for(int i=0;i<5;i++){
            B[i] = new CBall();
            t[i] = new Thread(B[i]);
        }
       for(int i=0;i<5;i++){
           t[i].start();
       }
    }
}

class Character extends JPanel implements KeyListener,Runnable{ //人物
    int x = 0, xa = 0;
    public void run(){
        Graphics g = getGraphics();
        paint(g);
    }
    public void paint(Graphics g){ //繪出人物先用矩形代替
        g.setColor(Color.blue);
        g.drawRect(100, 660, 120, 20);
    }
    public void keyReleased(KeyEvent e) {...}
    public void keyPressed(KeyEvent e) {...}
    public void keyTyped(KeyEvent e){}
}

尚未有邦友回答

立即登入回答