当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to Successfully add the MenuBar with the Buttons in place?

问题描述:

This is my code, but the MenuBar Refuses to show up. How do I add the menu bar to get it to pull up? The only thing that shows up is the buttons. If I add something, the frame will refuse to show the menu. Please tell me what I did wrong, thanks in advance.

import javax.swing.*;

import java.awt.*;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.*;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

public class MyFrame extends JFrame implements ActionListener {

public MyFrame() {

JFrame frame = new JFrame("MyFrame");

this.getContentPane().setLayout(new FlowLayout());

JButton ExitBtn = new JButton();

ExitBtn.setText("Exit");

ExitBtn.addActionListener(this);

JButton Find = new JButton("Find");

JButton Clear = new JButton("Clear");

// add buttons to frame

add(ExitBtn);

add(Find);

add(Clear);

JMenuBar menuBar = new JMenuBar();

JMenu menu = new JMenu("Menu");

menuBar.add(menu);

JMenuItem item = new JMenuItem("Exit");

menu.add(item);

}

public void actionPerformed(ActionEvent e){

System.exit(0);

//ExitBtn.addActionListener(this);

}

public static void main(String[] args) {

new MyFrame();

MyFrame mf = new MyFrame();

mf.pack();

mf.setSize(800, 650);

mf.setVisible(true);

mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

网友答案:

You haven't added your JMenuBar to the JFrame and hence it won't show. Add it to your JFrame just as you would add other JComponents :)

网友答案:

Just call setJMenuBar() in the MyFrame constructor. Like so:

setJMenuBar(menuBar);

Also this isn't related to your original question but you should probably remove the first new MyFrame(); from your main method. It's unnecessary since you're already creating another instance of your GUI directly below that.

分享给朋友:
您可能感兴趣的文章:
随机阅读: