JPanel无法显示 [英] JPanel won't display

查看:224
本文介绍了JPanel无法显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级,该班级应该启动游戏(使用main())和游戏的开始屏幕.扩展了JFrame的具有main()的类(名为Starter),创建了一个新的OpeningScreen类(扩展了JPanel),并将其添加到JFrame中.

I got a class that's supposed to launch a game (with main()), and the game's opening screen. The class with main() (named Starter), that extends JFrame, creates a new OpeningScreen class (extending JPanel), and adds it to the JFrame.

由于某些原因,OpeningScreen不会添加到JFrame中.代码:

For some reason, the OpeningScreen won't be added to the JFrame. Code:

Starter类:

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

public class Starter extends JFrame {

    public Starter(){

        setSize(500,500);
        setResizable(false);
        setTitle("Ping-Pong Battle");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        OpeningScreen openingS = new OpeningScreen();
        add(openingS);

        setVisible(true);

    }

    public static void main(String[]args){
        Starter starter = new Starter();
    }

}

OpeningScreen类:

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;

public class OpeningScreen extends JPanel {

    public OpeningScreen(){
        setBackground(Color.BLACK);
        setFocusable(true);
            setVisible(true);
    }

    public void paint(Graphics g){

        // Soon code here to be drawn.

    }

    public void startGame(){
        Board board = new Board();
    }

}

出什么问题了?谢谢

OpeningScreen的构造函数可以运行,但是不会将背景涂成黑色.另外,尝试在paint()中绘制东西也不起作用.

The constructor of OpeningScreen does run, but doesn't paint the background black. Also, trying to draw things in paint() doesn't work.

推荐答案

您的问题是由在您的OpeningScreen类中覆盖paint引起的.没有绘制背景,因为您从不绘制背景!呼叫super.paint(g)修复此问题.

Your problem arises from overriding paint in your OpeningScreen class. The background is not drawn because you never draw it! Call super.paint(g) to fix this.

但是,通常建议使用paintComponent()代替paint().只需将代码移至paintComponent.

However, it is generally recommended to use paintComponent() instead of paint(). Just move your code to paintComponent.

此方法可以正确地在黑色背景上绘制红色正方形:

This method correctly draws a black background a red square:

@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);
    g.fillRect(100, 100, 100, 100);
}

这篇关于JPanel无法显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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