I cannot figure out why my menu bar isn't visible. I have following code:
//Main
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Menu extends JFrame{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(500,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
menuBar mbObj = new menuBar();
mbObj.menuBar(frame);
}
}
//Menu Bar class
public class menuBar{
private JMenu file,edit;
private JMenuItem nFile ,oFile,sFile,saFile,exit;
private JMenuItem undo,copy,paste;
private JMenuBar bar;
public void menuBar(JFrame frame){
bar = new JMenuBar();
frame.setJMenuBar(bar);
bar.setVisible(true);
file = new JMenu("File");
edit = new JMenu("Edit");
bar.add(file);
bar.add(edit);
}
}
Call
setVisible(true)
on the top-level window, here a JFrame, only after adding all components, including theJMenuBar
. You will also want to avoid callingsetSize(...)
on anything, and instead use layout managers and callpack()
on the JFrame after adding all components and before callingsetVisible(true)
.So the order should be:
As an aside class names should begin with an upper case letter, and dont have methods with the exact same name as the class, as that creates a "pseudo"-constructor and will confuse everyone.