使用Java中的线程在JPanel上绘画

时间:2015-08-11 15:13:04

标签: java multithreading swing

我想使用Java中的线程重绘()我的JPanel。

我正在使用两个不同的类。

具有JFrame(主类)的类和另一个扩展JPanel的类。

以下是课程:

这是自己的框架

public class Frame {
    static int width = 1280 ;
    static int height = 720 ;

public Frame(){
        InGamePanel inGame = new InGamePanel();
        JFrame menu = new JFrame();
        Menu.setSize(width, height);
        Menu.setTitle("STICK FACTORY");
        Menu.setResizable(false);
        Menu.add(InGame);
        Menu.setVisible(true);
    }

    public static void main(String[] args) {
        new Frame();

    }

}

这一个是Thread的on,它没有运行:

import javax.swing.JPanel;

import BackGround.BackGround;
import Enums.Player;
import Enums.Stick;

public class InGamePanel extends JPanel implements KeyListener{

    //Thread for FPS
    FPS reloader = new FPS();

    //Background
    BackGround gameBG = new BackGround(Frame.width , Frame.height);

    //Player
    int xPosition_Player = 400;
    int yPosition_Player = 180;
    Player jeff = new Player();

    //Stick 
    int xPosition_Stick = 600 ;
    int yPosition_Stick = 180 ;
    Stick fluffy = new Stick();

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        gameBG.drawBackGround(g);
        jeff.drawPlayer(g, XPosition_Player, YPosition_Player);
        fluffy.drawStick(g, XPosition_Stick, YPosition_Stick);
        reloader.run();
    }







    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyChar() == 's'){
            yPosition_Player+= 40 ;
            jeff.direction = 's';
        }
    }




    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }




    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }   


    class FPS implements Runnable{

        int fps = 60 ;
        @Override
        public void run() {
            try {
                Thread.sleep(1000 / fps);
                repaint();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }


}

那么如何让Thread运行并重新绘制我的程序呢?

0 个答案:

没有答案