简体   繁体   English

JPanel出现在JMenuBar的后面

[英]JPanel Appears Behind JMenuBar

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

@SuppressWarnings("serial")
public class Main extends JFrame {

    final int FRAME_HEIGHT = 400;
    final int FRAME_WIDTH = 400;

    public static void main(String args[]) {
        new Main();
    }

    public Main() {
        super("Game");

        GameCanvas canvas = new GameCanvas();

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem startMenuItem = new JMenuItem("Pause");
        menuBar.add(fileMenu);
        fileMenu.add(startMenuItem);

        getContentPane().add(canvas);
        super.setVisible(true);
        super.setSize(FRAME_WIDTH, FRAME_WIDTH);
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        super.setJMenuBar(menuBar);
    }
}


import java.awt.Canvas;
import java.awt.Graphics;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class GameCanvas extends JPanel {

    public void paint(Graphics g) {
        g.drawString("hI", 0, 0);
    }
}

This code causes the string to appear behind the JMenuBar. 此代码使字符串出现在JMenuBar的后面。 To see the string, you must draw it at (0,10). 要查看该字符串,必须在(0,10)处绘制它。 I'm sure this must be something simple, so do you guys have any ideas? 我敢肯定这一定很简单,所以你们有什么想法吗?

Try 尝试

FontMetrics fm = g.getFontMetrics();
g.drawString("hI", 10, fm.getMaxAscent());

as suggested by the diagram in FontMetrics . FontMetrics的图表所建议。

Addendum: @RaviG is right, too. 附录:@RaviG也正确。

You have not added your canvas to the frame. 您尚未将画布添加到框架。

In your constructor, at the end, 最后,在您的构造函数中,

add getContentPane().add(canvas); 添加getContentPane().add(canvas);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM