Add Menu Bar

Learn to add code for a menu bar with an option to use the sliding image with another image instead of the flower one.

The Sliding Tiles program is a good example of a program that would benefit from a menu bar. A menu bar could be added to allow the user to choose a different image or to change the number of tiles in the grid.

Menu bars

Buttons are not the only way to get action requests from the program user. Many programs use a menu bar.

Adding a menu bar with one menu item

  1. At the beginning of initGUI(), add comments for a menu bar section and a title section.
    ...
 
  private void initGUI() {
 
    // menu bar
 
    // title
    TitleLabel titleLabel = new TitleLabel("Sliding Tiles");
    add(titleLabel, BorderLayout.PAGE_START);
 
      ...

Add a menu bar with a File menu that has an option to open a different image.

  1. In the menu bar section of initGUI(), create a new JMenuBar object called menuBar, initialized by calling JMenuBar's constructor.
  2. Set the window’s menu bar to menuBar using JFrame's setJMenuBar() method.
  3. Create a new JMenu object called fileMenu, initialized by calling JMenu's constructor with “File” as the parameter value.
  4. Add fileMenu to menuBar using JMenuBar's add() method.
  5. Create a new JMenuItem object called openMenuItem, initialized by calling JMenuItem's constructor with “Open” as the parameter value.
  6. Add openMenuItem to fileMenu using JMenu's add() method.
    ...
private void initGUI() {
 
    // menu bar
    _____________ menuBar = _____________;
    setJMenuBar(__________);
    
    _____________ fileMenu = ____________;
    menuBar._____________;
    
    _____________ openMenuItem = _______________;
    fileMenu.____________;
    
      ...

Get hands-on with 1200+ tech skills courses.