I'm trying to get the Java Swing JMenuBar
element working correctly. My app has several menu elements. The problem is when the user resizes the window to be smaller than the menu elements size. What happens is that the menu elements get compressed and endup overlaping each other instead of using more lines. Is there any way to have the JMenuBar
JMenu
elements to break line when there is not enough space?
ExampleCode:
frame = new JFrame();
frame.setBounds(100, 100, 722, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnNewMenu = new JMenu("New menu");
menuBar.add(mnNewMenu);
JMenu mnNewMenu_1 = new JMenu("New menu");
menuBar.add(mnNewMenu_1);
JMenu menu = new JMenu("New menu");
menuBar.add(menu);
JMenu menu_1 = new JMenu("New menu");
menuBar.add(menu_1);
JMenu menu_2 = new JMenu("New menu");
menuBar.add(menu_2);
JMenu menu_3 = new JMenu("New menu");
menuBar.add(menu_3);
JPanel split = new JPanel();
frame.getContentPane().add(split, BorderLayout.CENTER);
split.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
JButton btnNewButton = new JButton("New button");
JButton btnNewButton_1 = new JButton("New button");
JButton btnNewButton_2 = new JButton("New button");
split.add(panel, BorderLayout.CENTER);
JLabel lblTextContentBla = new JLabel("Text content bla bla bla");
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
panel.add(btnNewButton);
panel.add(btnNewButton_1);
panel.add(btnNewButton_2);
panel.add(lblTextContentBla);
Screenshots:
(P.D: Is StackOverflow broken? When I post pictures it says that it found unformatted code. Had to post the links as code with no previews to make it work.. ??)
The default layout manager for a JMenuBar is the DefaultMenuLayout
which extends the BoxLayout
. This layout does not support wrapping.
You can try using the Wrap Layout to see if it meets your requirements. This layout extends FlowLayout
and allows components to wrap to a new line.
The basic code would be:
JMenuBar menubar = new JMenuBar();
menuBar.setLayout( new WrapLayout(WrapLayout.LEFT, 0, 0) );
You would gain wrapping support, but would lose other BoxLayout features. If it doesn't meet your requirements, then you would need to write your own custom LayoutManager
.