JPanel 未绘制,JFrame 保持空白 [英] JPanel not painting, JFrame remains blank

查看:54
本文介绍了JPanel 未绘制,JFrame 保持空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款类似数字口袋妖怪卡片的游戏.当我尝试绘制任何图像时,JFrame 保持为空.这可能是一个简单的错误,但我一直无法找到解决方案.在 Stack Overflow 上,我看到了很多像我这样的问题,尽管他们的解决方案对我的代码不起作用.这是代码:JFrame 的类:

I'm working on a digital Pokemon card-like game. When I try to paint any of my images, the JFrame remains empty. It may be a simple error, but I have not been able to find a solution. On Stack Overflow, I have seen many issues like mine though their solutions don't work on my code. Here's the code: The class for the JFrame:

import javax.swing.JFrame;


public class Rocks extends JFrame{

public Rocks(){
    setVisible(true);
    setTitle("Rocks Card Game");
    setSize(1200,297);
    add(new Display());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
    new Rocks();
}

}

JPanel 类:

    import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;


public class Display extends JPanel{
    Image granite;
    public Display(){
        granite = new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png").getImage();
        setBackground(Color.black);
    }
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(granite,0,0,null);
    }
}

推荐答案

移动 setVisible(true); 到 Rocks 构造函数的底部.

Move setVisible(true); to the bottom of the Rocks constructor.

为什么应该最后调用 setVisible() 的说明

这篇关于JPanel 未绘制,JFrame 保持空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆