简体   繁体   English

如何将菜单栏类添加到主类中的JFrame中

[英]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. 我不确定将MenuDriver类连接到Main类中的JFrame的代码。 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. 在MenuDriver类中,您需要创建一个方法getMenuBar() ,该方法将返回在类的构造函数中创建的JMenuBar。

Then you need to make the JMenuBar an instance variable of the class: 然后,需要使JMenuBar成为该类的实例变量:

public class MenuDriver 
{
    private JMenubar menuBar; // added

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

I'll let you write the getMenuBar() method. 我将让您编写getMenuBar()方法。

Now in you main class you can reference the menu bar by using: 现在在您的主类中,您可以使用以下命令引用菜单栏:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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