I'm learning about GUI in Java.
I'm slightly confused here. When I place window.setVisible(true);
like this, I only see JMenuBar if I resize it (it doesn't show without some sort of interaction).
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
}
}
But when I place it at the very bottom, it shows as expected. Why is this?
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
window.setVisible(true);
}
}
Here it is explained that it must be called at the end, but what is the reasoning behind this?
After adding a component you would have to repaint the container. So if you add menubar after window is visible, it will popup after next repaint, in your example, after resize. If menubar is added prior setting window to be visible, it will be drawn at first drawing.
This is common behaviour for Swing components.
If you add or remove component:
If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.