JFrame背景覆盖菜单栏

时间:2012-02-27 22:26:34

标签: java swing background jframe jmenu

每当我向我的JFrame添加背景(Image img)时,我都无法看到我的菜单栏....任何帮助都会非常感激...我只是在学习JFrames,我可能会忽略一些愚蠢的事情。 / p>

class GameFrame extends JFrame {

private JLabel statusbar;
Image img = new ImageIcon("splash.png").getImage();

public GameFrame() {
    initUI();
    menuUI();
    BackgroundLoader bg = new BackgroundLoader();
}

@Override
    public void paint(Graphics g) {
    try {
        Image img = ImageIO.read(new File("splash.png"));             
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public final void initUI() {
    setTitle("Super RPG Hero: The Quest for Fame and Fortune");
    setSize(800, 480);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //JLabel background = new JLabel(splash);
    //background.setBounds(0, 0, splash.getIconWidth(), splash.getIconHeight());
    //getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));

}

public final void menuUI() {


    JMenuBar menubar = new JMenuBar();

    //Creates file menu item
    JMenu file = new JMenu("File");
    file.setMnemonic(KeyEvent.VK_F);

    //Creates Object for New Game toolbar
    JMenuItem newItem = new JMenuItem("New Game");
    newItem.setMnemonic(KeyEvent.VK_C);
    newItem.setToolTipText("New Game");
    newItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            String playerName = "Peter";
            CharacterCreator characterOne = new CharacterCreator(playerName);
            characterOne.statBuilder();
        }
    });

    //Creates Object for Save Game toolbar
    JMenuItem saveItem = new JMenuItem("Save");
    saveItem.setMnemonic(KeyEvent.VK_C);
    saveItem.setToolTipText("Save Game");

    //Creates Object for Load Game toolbar
    JMenuItem loadItem = new JMenuItem("Load");
    loadItem.setMnemonic(KeyEvent.VK_C);
    loadItem.setToolTipText("Load Game");

    //Creates Object for Exit Game toolbar
    //And creates method for the game to exit
    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.setMnemonic(KeyEvent.VK_C);
    exitItem.setToolTipText("Exit Game");
    exitItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });

    //Adds created objects to GUI
    file.add(newItem);
    file.add(saveItem);
    file.add(loadItem);
    file.add(exitItem);
    menubar.add(file);

    setJMenuBar(menubar);

}

}

1 个答案:

答案 0 :(得分:4)

您应该实施paintComponent()而不是paint()

通过覆盖绘画而不是委托,你不会让JFrame描绘它需要绘画的东西。

另外,请查看此answer