I seem to have done everything correct. I just need to implement a simple JMenuBar
but it seems to be not working. Can someone please help me out in this?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class swing {
public static void main (String[] args) {
JFrame frame = new JFrame ("menu");
frame.setVisible (true);
frame.setSize (400, 400);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar ();
frame.setJMenuBar (bar);
bar.setVisible (true);
JMenu file = new JMenu ("File");
bar.add (file);
JMenuItem open = new JMenuItem ("open");
file.add(open);
}
}
What you are doing is displaying frame first and then add menu bar to it. It will not work. You should do reverse. Shift frame.setVisible (true);
line at the end or at least after setting menu bar. You should always display frame after adding all components to it or else components added after displaying frame will not appear until repaint()
is done.
From the comment by @sjr :
Sometimes
revalidate
is required (not onlyrepaint
) as altering a container (adding/removing/resizing components) after the container has been displayed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With