JPanel won't display

我与影子孤独终老i 提交于 2019-12-12 01:04:22

问题


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.

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

Starter class:

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 class:

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();
    }

}

What's the problem? Thanks

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


回答1:


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.

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);
}



回答2:


I think because you override paint() the background doesn't get painted, so it appears like the Panel isn't added. Commenting out the paint method results in the Window being black for me.
Also, drawing in the paint method works for me, maybe your color is set to black so it doesn't show on the black background ? Try g.setColor(Color.white) before drawing.



来源:https://stackoverflow.com/questions/20830382/jpanel-wont-display

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!