Code Completion 11.102 Lay out a menu
Lay out a menu to look like the screen capture below.
Here is a sample program output:
Complete the following code:
import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; public class MenuFrame extends JFrame { private JMenuBar menuBar; private JMenu fileMenu; private JMenu editMenu; private JMenu aboutMenu; private JMenuItem item1; private JMenuItem item2; private JMenuItem item3; private JMenuItem item4; public MenuFrame() { item1 = new JMenuItem("Open File"); // put in File menu item2 = new JMenuItem("Exit"); // put in File menu item3 = new JMenuItem("Search"); // put in Edit menu item4 = new JMenuItem("About MenuFrame"); // put in About menu ... } }
The following class is used to check your work:
import javax.swing.JFrame; public class MenuFrameViewer { public static void main(String[] args) { MenuFrame frame = new MenuFrame(); frame.setTitle("MenuFrameViewer"); frame.setBounds(100,100, 300,200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Expert Answer
import java.awt.Menu;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class MenuFrame extends JFrame
{
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu editMenu;
private JMenu aboutMenu;
private JMenuItem item1;
private JMenuItem item2;
private JMenuItem item3;
private JMenuItem item4;
public MenuFrame()
{
item1 = new JMenuItem(“Open File”); // put in File menu
item2 = new JMenuItem(“Exit”); // put in File menu
item3 = new JMenuItem(“Search”); // put in Edit menu
item4 = new JMenuItem(“About MenuFrame”); // put in About menu
fileMenu = new JMenu(“File”);
fileMenu.add(item1);
fileMenu.add(item2);
editMenu = new JMenu(“Edit”);
editMenu.add(item3);
aboutMenu = new JMenu(“About”);
aboutMenu.add(item4);
menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
this.setJMenuBar(menuBar);
}
}