Insert vertical separator between icon and text in JMenuItem
I am trying to insert / display a vertical separator between the icon and text of JMenuItem components in my applications. I am creating JMenuItem like this (roughly):
JMenuItem cutMenuItem = new JMenuItem();
cutMenuItem.setName("cutMenuItem");
cutMenuItem.setRequestFocusEnabled(false);
cutMenuItem.setText("cut");
cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
When I go through the items in the menu, they look like this:
Interestingly, I noticed that the look of the JMenu components matches the look I want:
Naturally changing all JMenuItem components to JMenu components is not a viable solution. How can I get JMenuItem components in my application to have a vertical divider / border between the icon and the text?
Is this hinge on L&F? For the record, I'm on a Windows 7 machine. I tried to set the LayoutManager on the JMenuItems in the BorderLayout:
cutMenuItem.setLayout(new BorderLayout(5,0));
Expecting to see a horizontal gap between the icon and the text, but that didn't seem to make any difference.
EDIT: Here's a very fundamental SSCCE
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
public class FakeApp {
public static void main(String args[]) {
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem = new JMenuItem();
menuItem.setName("cutMenuItem");
menuItem.setRequestFocusEnabled(false);
menuItem.setText("cut");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
menuItem.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
menu.add(menuItem);
menuBar.add(menu);
frame.getRootPane().setJMenuBar(menuBar);
frame.add(new JPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300));
frame.pack();
frame.setVisible(true);
}
}
source to share