直接在Graphics对象上重载paintComponent()或绘图?

时间:2014-11-01 20:03:06

标签: java swing jframe jpanel

我试图通过制作一个小游戏来学习Java和Swing(我现在不需要表演)。我使用Swing管理我的游戏窗口(JFrame)并渲染游戏场景(JPanel)。我找到了两种方法来实现相同的结果:重载JPanel.paintComponent并直接在其Graphics对象上绘制。以下是两个示例(我导入整个awt和swing包以避免错误,因为我是从另一台PC写的):

第一种方法:

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

public class Game
{
    private static JFrame f;

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() ->
        {
            f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setResizable(false);
            f.setContentPane(new JPanel()
            {
                @Override
                protected void paintComponent(Graphics g)
                {
                    super.paintComponent(g);
                    // I'm doing my paint operations here
                }
            });
            f.getContentPane().setPreferredSize(new Dimension(320, 240));
            f.pack();
            f.setVisible(true);
        });

        while(true)
        {
            // Game logic should go here
            SwingUtilities.invokeLater(() ->
            {
                if(f == null)
                    return;

                f.repaint();
            });

            try
            {
                Thread.sleep(1000 / 60); // Cap FPS to 60
            }
            catch(InterruptedException ex)
            {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }
}

第二种方法:

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

public class Game
{
    private static JFrame f;

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() ->
        {
            f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setResizable(false);
            f.setContentPane(new JPanel());
            f.getContentPane().setPreferredSize(new Dimension(320, 240));
            f.pack();
            f.setVisible(true);
        });

        while(true)
        {
            // Game logic should go here
            SwingUtilities.invokeLater(() ->
            {
                if(f == null)
                    return;

                Graphics g = f.getContentPane().getGraphics();
                // Paint operations ...
                g.dispose();
            });

            try
            {
                Thread.sleep(1000 / 60); // Cap FPS to 60
            }
            catch(InterruptedException ex)
            {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }
}

最简单的方法是什么?为什么? 我的第二个奖励问题是:有没有办法用Swing管理我的窗口但是使用OpenGL绘制东西?

PS:抱歉英文不好!

0 个答案:

没有答案