Java面板不会绘制

时间:2012-03-23 00:36:40

标签: java swing jpanel repaint

基本摘要:处理一个生成15x15网格的游戏,让玩家可以四处移动。网格中的每个单元格都是随机生成的棕色阴影,因此每个单元格看起来都不同。唯一的问题是我正在尝试为每个包含随机颜色系列的单元格创建缓冲图像。我在Dirt类中的问题是它不会调用paintComponent方法。这是Dirt课程。 (在构造函数中传入单元格的矩形)

package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class Dirt extends JPanel{
    private Rectangle rect;
    private BufferedImage image;
    private int pixelSize;

    public Dirt(Rectangle x){
        rect = x;
        image = new BufferedImage(rect.width, rect.width, BufferedImage.TYPE_INT_RGB);
        pixelSize = rect.width/15;
        setVisible(true);
        validate();
        this.repaint();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = image.createGraphics();
        Rectangle[][] rects = new Rectangle[15][15];
        Color[] colors = {new Color(160,82,45),new Color(139,69,19),new Color(165,42,42)};
        java.util.Random randomGenerator = new java.util.Random();
        for(int i = 0; i < 15; i++){
            for(int j = 0; j < 15; j++)
                rects[i][j] = new Rectangle(pixelSize*i,pixelSize*j,pixelSize,pixelSize);
        }
        for(int i = 0; i < 15; i++){
            for(int j = 0; j < 15; j++){
                System.out.println(i + " " + j);
                g2d.setColor(colors[randomGenerator.nextInt(3)]);
                g2d.fillRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
            }
        }
        g2d.dispose();
    }

    public Image getImage(){return image;}
    public Rectangle getRect(){return rect;}
}

1 个答案:

答案 0 :(得分:2)

将以下内容添加到paintComponent方法的末尾:

g.drawImage(image, 0, 0, this);

就像@Carl Manaster在他的评论中所说,你已经吸引了缓冲的图像,但是你不会将缓冲的图像绘制到传递给paintComponent方法的Graphics对象中。

编辑:我在您的课程中添加了以下内容进行测试,并将上面的代码行包含在paintComponent方法中,它适用于我:

public static void main(String args[]) {
    JFrame f = new JFrame();

    f.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }

    });

    f.getContentPane().setLayout(null);

    Dirt d = new Dirt(new Rectangle(40, 40));
    d.setBounds(20, 20, 64, 64);
    f.getContentPane().add(d);

    f.setSize(300, 300);

    f.setVisible(true);
}