简体   繁体   中英

Adding a JMenuBar to a JFrame from another class

I've created a class which holds a basic JFrame and another class which holds code for a JMenu but when I try to call the JMenu in the window class I am unable to use setJMenu(). I am not sure what I am missing can someone help?

Window.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class Window {
    JFrame frame;

    Menubar m = new Menubar();

    Window(){
        frame = new JFrame("Test Frame");

        frame.setJMenuBar(m);
        frame.setSize(200, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Menubar.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Menubar {
    JMenuBar menubar;
    JMenu menu;
    JMenuItem item1;

    Menubar(){
        menubar = new JMenuBar();
        menu = new JMenu("File");
        item1 = new JMenuItem("item");

        menubar.add(menu);
        menu.add(item1);
        
    }
}

VS Code tells me to use getJMenu which also does not work.

Your problem is simply that you are not exposing the JMenuBar in MenuBar

Rather than your MenuBar() constructor, add this

public static JMenuBar createMenuBar(){
    menubar = new JMenuBar();
    menu = new JMenu("File");
    item1 = new JMenuItem("item");

    menubar.add(menu);
    menu.add(item1);
    return menu;
}

And in Window

Window(){
    frame = new JFrame("Test Frame");
    frame.setJMenuBar(MenuBar.createMenuBar());

Of course the problem then is that you don't have an Action added to the JMenuItem in your menu bar, which is why it is often better to build the entire GUI in one class... unless you also add API to do things like set the button's Action through a method in Window

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