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
- 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.
- In the menu bar section of
initGUI()
, create a newJMenuBar
object calledmenuBar
, initialized by callingJMenuBar
's constructor. - Set the window’s menu bar to
menuBar
usingJFrame
'ssetJMenuBar()
method. - Create a new
JMenu
object calledfileMenu
, initialized by callingJMenu
's constructor with“File”
as the parameter value. - Add
fileMenu
tomenuBar
usingJMenuBar
'sadd()
method. - Create a new
JMenuItem
object calledopenMenuItem
, initialized by callingJMenuItem
's constructor with “Open” as the parameter value. - Add
openMenuItem
tofileMenu
usingJMenu
'sadd()
method.
...
private void initGUI() {
// menu bar
_____________ menuBar = _____________;
setJMenuBar(__________);
_____________ fileMenu = ____________;
menuBar._____________;
_____________ openMenuItem = _______________;
fileMenu.____________;
...
Get hands-on with 1200+ tech skills courses.