简体   繁体   中英

How do I add my menubar class to my JFrame which is in my Main Class

I am unsure on the code to connect my MenuDriver class to my JFrame which is in Main class. I understand that this could all be done in the main class, but I am being told to have a separate class for the menu.

Main-
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.MenuBar;

import javax.swing.JFrame;

public class GraphicMain {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Graphics Program");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 600);

        MenuDriver menu = new MenuDriver();

        frame.pack();
        frame.setVisible(true);
    }
}

Menu Class-

import java.awt.*;

import javax.swing.*;
public class MenuDriver {

    public MenuDriver(){
        JMenuBar menubar = new JMenuBar();

        JMenu file = new JMenu("File");
        menubar.add(file);

        JMenuItem load = new JMenuItem("Load");
        file.add(load);

        JMenuItem save = new JMenuItem("Save");
        file.add(save);

        JMenuItem exit = new JMenuItem("Exit");
        file.add(exit);

        JMenu help = new JMenu("Help");
        menubar.add(help);

        JMenuItem info = new JMenuItem("Info");
        file.add(info);
        }
}

In your MenuDriver class you need to create a method getMenuBar() which will return the JMenuBar that you created in the constructor of your class.

Then you need to make the JMenuBar an instance variable of the class:

public class MenuDriver 
{
    private JMenubar menuBar; // added

    public MenuDriver()
{
        //JMenuBar menubar = new JMenuBar();
        menubar = new JMenuBar();
        ...

I'll let you write the getMenuBar() method.

Now in you main class you can reference the menu bar by using:

MenuDriver menu = new MenuDriver();
frame.setJMenuBar( menu.getMenuBar() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM