I have a JFrame that I want to add a menu bar to and then have that JFrame automatically open in fullscreen. If I just make a JFrame and set it to fullscreen with f.setExtendedState(f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
that works fine:
import javax.swing.*;
public class testframe {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(testframe::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
f.pack();
f.setVisible(true);
}
}
However, once I add a JMenuBar to that JFrame it will no longer open in fullscreen:
import javax.swing.*;
public class testframe {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(testframe::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
JMenuBar menubar = new JMenuBar();
JMenu j_menu = new JMenu("Test");
JMenuItem j_menu_item = new JMenuItem("Test_item");
j_menu.add(j_menu_item);
menubar.add(j_menu);
f.setJMenuBar(menubar);
f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
f.pack();
f.setVisible(true);
}
}
What could be the cause for this?
Update:
Switching to JDK11 solved the problem. I was on 15 before and also tried 14, both had the problem.
You need to call the JFrame
methods in the correct order.
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class TestFrame {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(TestFrame::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu j_menu = new JMenu("Test");
JMenuItem j_menu_item = new JMenuItem("Test_item");
j_menu.add(j_menu_item);
menubar.add(j_menu);
f.setJMenuBar(menubar);
f.pack();
f.setExtendedState(f.getExtendedState() | JFrame.MAXIMIZED_BOTH);
f.setVisible(true);
}
}
once I add a JMenuBar to that JFrame it will no longer open in fullscreen:
Appears in full screen for me. I use JDK11 in Windows 10.
However, the menu doesn't work because you have a coding problem. You need to add the JMenu to the JMenubar.
//menubar.add(j_menu_item);
menubar.add(j_menu);
Also, I've always just used:
f.setExtendedState( JFrame.MAXIMIZED_BOTH );
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.