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.
CodePudding user response:
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