创建后绘制组件

时间:2015-09-03 09:08:13

标签: java swing awt

要用Java创建我的第一个2D游戏,我想到使用JFrame的{​​{1}},每50ms用新视图更新它。

getContentPane()

但它不起作用;窗口没有变化。

2 个答案:

答案 0 :(得分:1)

正如kiheru所说,使用paintComponent(Graphics g)进行自定义绘画。这是一个例子:

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class Example {

    int i = 0;

    public Example() {

        JFrame frame = new JFrame();

        frame.getContentPane().add(new DrawingPanel());

        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        ActionListener actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                frame.getContentPane().repaint();

            }

        };

        Timer timer = new Timer(500, actionListener); //500 = Every 500 milliseconds
        timer.start();

    }

    class DrawingPanel extends JPanel {

        @Override
        public void paintComponent(Graphics g) {

            super.paintComponent(g); // Removes previous graphics

            Random r = new Random(); //Randomizer

            //Random x- and y-coordinates
            int x = r.nextInt(400);
            int y = r.nextInt(400);

            //Random rgb-values
            int red = r.nextInt(255); 
            int green = r.nextInt(255);
            int blue = r.nextInt(255);

            //Random width and height
            int width = r.nextInt(100);
            int height = r.nextInt(100);

            g.setColor(new Color(red, green, blue)); //Setting color of the graphics

            g.fillRect(x, y, width, height); //Filling a rectangle

        }

    }

    public static void main(String[] args) {

        new Example();

    }

}

答案 1 :(得分:0)

研究双缓冲或使用VolatileImage类型进行快速图像绘制以直接转换为图形卡。在您的情况下,如果您使用双缓冲,代码将是:

private static BufferedImage bufferedImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
    private static Graphics2D gBuff = bufferedImage.createGraphics();

    public static void main(String[] args)
    {
        JFrame frame = new JFrame()
        {
            @Override
            public void paint(Graphics g)
            {
                g.drawImage(bufferedImage,0,0,this);
            }
        };
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        gBuff.setColor(Color.WHITE);
        gBuff.fillRect(0, 0, frame.getWidth(), frame.getHeight()); // Remove previous drawing
        gBuff.setColor(Color.BLACK);
        gBuff.drawString("Text", 50, 50);


        // ...
        frame.setVisible(true);
        // ...
    }