I need two columns of menu items in a menu. This can be achieved using the GridBagLayout for a popup menu. My problem is: both column have the same width which is the width of the largest menu item in the menu (but not in column as it must be for GridBagLayout). When I replace menu items in the menu by buttons - the layout works correct. So how can i advice a menu that the items should have different widths?
Here are the screens:
When I use menu items - both columns have the same width (wrong)
When I use buttons - columns have different widths (correct)
Here is the code example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class MenuTest {
public static void main(String[] args) {
JFrame frm = new JFrame("Menu test");
JMenuBar menuBar = new JMenuBar();
JMenu m1 = new JMenu("Menu items");
m1.getPopupMenu().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
m1.getPopupMenu().add(new JMenuItem("Very very very very long text"), gbc);
gbc.gridx = 1;
m1.getPopupMenu().add(new JMenuItem("Short text"), gbc);
menuBar.add(m1);
JMenu m2 = new JMenu("Buttons");
m2.getPopupMenu().setLayout(new GridBagLayout());
gbc.gridx = 0;
m2.getPopupMenu().add(new JButton("Very very very very long text"), gbc);
gbc.gridx = 1;
m2.getPopupMenu().add(new JButton("Short text"), gbc);
menuBar.add(m2);
frm.setJMenuBar(menuBar);
frm.add(new JScrollPane(new JTextArea("Sample text", 10, 40)));
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setVisible(true);
}
}