JPanel 更改未显示在 Jframe 上

JPanel changes not showing on Jframe

您好,我正在尝试使用 JPanel 和 JFrame 创建一个 java 游戏。但是我无法让 JPanel 显示我对其所做的更改。我想知道我是否可能错误地设置了 JFrame 或不正确地添加到它或类似的东西。

这是我的 window class:

import javax.swing.*;
import java.awt.*
public class Window extends Canvas {

public static final int ScreenWidth = 1000;
public static final int ScreenHeight = 700;
public static JFrame frame;

Window(int ScreenWidth, int ScreenHeight, JFrame frame) {
    this.frame = frame;
    displaywindow();
    frame.add(this);
}

public void paint(Graphics g) {
    super.paint(g);
}

public void displaywindow() {
    this.frame.setPreferredSize(new Dimension(ScreenWidth,ScreenHeight));
    this.frame.setMaximumSize(new Dimension(ScreenWidth,ScreenHeight));
    this.frame.setMinimumSize(new Dimension(ScreenWidth,ScreenHeight));
    this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.frame.setResizable(false);
    this.frame.setBackground(Color.pink);
    this.frame.setLocationRelativeTo(null);
}

public JFrame getFrame() {
    return this.frame;
}

}

这是我正在处理的菜单 class:

public class Menu extends JPanel implements ActionListener, KeyListener {
private Window win = new Window(Window.ScreenWidth, Window.ScreenHeight, Window.frame);
private int width = Window.frame.getContentPane().getWidth();
private int height = Window.frame.getContentPane().getHeight();
BufferedImage bg;
  
Menu(JPanel panel) {
    this.panel = panel;
}
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.fillRect(110, 110, 20, 20);
}


public void init() throws IOException {
    this.panel.setBackground(Color.cyan);
    this.panel.setPreferredSize(new Dimension(width, height));
    this.panel.setMaximumSize(new Dimension(width, height));
    this.panel.setMinimumSize(new Dimension(width, height));
    JLabel start = new JLabel("Start");
    start.setFont(new Font("Verdana", Font.PLAIN, 50));
    start.setLocation(500, 400);
    this.panel.add(new JLabel("Exit"));
    this.panel.add(start);
    this.panel.revalidate();
    this.panel.repaint();
    this.panel.setVisible(true);
}

enter code here
public static void main(String[] args) throws IOException {
    
    Window win = new Window(Window.ScreenWidth, Window.HEIGHT, new JFrame());
    Menu mene = new Menu();
    mene.init();
    win.getFrame().getContentPane().add(mene);
    win.getFrame().setVisible(true);

}

我尝试向 paintComponent 添加一个矩形,这样我就可以确定面板确实被添加到了框架中并且它显示确实如此,但是 none 我在 init() 中所做的更改曾经真正展示过。任何帮助将不胜感激。

`

问题是您在 Menu class 中同时执行 class Menu extends JPanel 和声明 JPanel panel。这种重复是不必要的,并且会导致问题,因为您将项目添加到 panel 字段,但您从未对该面板执行任何操作。

另一方面,您声明 Menu mene 并将其添加到内容窗格,但您从未向 Menu 对象本身添加任何内容。不要这样混搭。选择字段成员或继承,但不能同时选择。