如何循环Swing程序而没有滞后

时间:2018-03-12 11:14:31

标签: java swing jframe jpanel

我目前正在编写一个小型2D游戏,它应该像马里奥一样跳跃和运行游戏。为了使变化可见,我有一个主循环来更新整个帧。不幸的是,这离开了整个窗口,如何在没有整个程序的情况下获得主循环?

gameStart:

public class gameStart
{
    public static void main(String[] args)
    {
        main jrg = new main();
    }
}

keylistener.java:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class keylisten implements KeyListener
{
    map map = mainframe.map;

    public void keyPressed(KeyEvent event)
    {
        char tmp = event.getKeyChar();

        System.out.println(tmp);

        if(tmp == 'D' || tmp == 'd')
        {
            map.setX(map.getX() + 10);
        }
        else if(tmp == 'A' || tmp == 'a')
        {
            map.setX(map.getX() - 10);
        }
        else if(tmp == 'W' || tmp == 'w' || tmp == ' ')
        {
            map.setY(map.getY() - 10);
        }
    }

    @Override
    public void keyReleased(KeyEvent event)
    {
        return;
    }

    @Override
    public void keyTyped(KeyEvent arg0)
    {
    }
}

main.java:

public class main
{
    mainframe mainframe = new mainframe();

    public main()
    {
        hauptschleife();
    }

    public void hauptschleife()
    {
        while(true)
        {
            mainframe.repaint();
        }
    }
}

mainframe.java:

import java.awt.BorderLayout;

import javax.swing.JFrame;

public class mainframe extends JFrame
{
    keylisten keys = new keylisten();
    static map map = new map();

    public mainframe()
    {
        setTitle("JRG2");
        setSize(500, 500);
        //Hauptfenster
        setLayout(new BorderLayout());

        add(map);
        addKeyListener(keys);

        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        repaint();

        setVisible(true);
    }
}

map.java:

import java.awt.Graphics;
import javax.swing.JPanel;

public class map extends JPanel
{
    public int x;
    public int y;

    public int getX()
    {
        return x;
    }

    public void setX(int x)
    {       
        if(x >= 0)
        {
            this.x = x;
        }
    }

    public int getY()
    {
        return y;
    }

    public void setY(int y)
    {
        if(y >= 0)
        {
            this.y = y;
        }
    }


    public map()
    {
        x = 10;
        y = 10;
    }

    public void paintComponent(Graphics g)
    {
        g.drawRect(x, y, 30, 40);
    }
}

祝你好运 托拜厄斯

0 个答案:

没有答案