将 JPanel 添加到 JLayeredPane 会导致无法调用 paint() 方法

Adding JPanel to JLayeredPane causes paint() method to not get called

为了提供一些可能有帮助的背景信息,我正在创建游戏 pong,我决定添加一个 escape/pause 菜单(当您在键盘上按 Esc 键时,会弹出一个包含一些设置的菜单),我环顾四周,发现最好的方法是使用 JLayeredPane 并在顶部添加另一个 JPanel。但是,当我将我的 'painter' class 添加到 JLayeredPane 时,paint(Graphics g) 方法停止被调用(当我将它添加到 JFrame 时它工作正常)。

import javax.swing.*;

public class Game extends JFrame {

    public static Painter painter;

    public Game() {
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLayeredPane lp = getLayeredPane();

        painter = new Painter();

        add(lp);
    }

    public static void main(String[] args) {
        Game frame = new Game();
        frame.setVisible(true);
        painter.repaint();
    }

}

这是我的 Painter class

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

public class Painter extends JPanel {

    public void paint(Graphics g) {
        System.out.println("Working");
        super.paint(g);
    }

}

而不是 add(lp);,我最初尝试 lp.add(painter);,在这种情况下,绘画方法从未被调用。通过执行 add(lp) 我得到一个 IllegalArgumentException 用于将容器的父级添加到自身。

这是使用 LayeredPane 的要点:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Game extends JFrame {

    public Game() {
        setSize(250, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLayeredPane lp = getLayeredPane();
        //assign layout manager. otherwise you need to set content
        //bounds (not recommended)
        lp.setLayout(new BorderLayout());
        Painter painter = new Painter();
        lp.add(painter,1);
    }

    public static void main(String[] args) {
        Game frame = new Game();
        frame.setVisible(true);;
    }
}

class Painter extends JPanel {

    @Override
    protected void paintComponent(Graphics g) { //do not override paint
        super.paintComponent(g);
        g.drawString("Working",50,50);
    }
}