Reputation: 1053
I'm trying to insert / display a vertical separator between the icon and the text of the JMenuItem components in my applications. I create a JMenuItem as follows (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 look at the items in the menu, they appear as follows:
Interestingly enough, I noticed that the default appearance of JMenu components matches the look that I want:
Naturally, changing all my JMenuItem components to JMenu components is not an acceptable solution. How can I get the JMenuItem components in my application have a vertical separator / border between the icon and the text?
Does this hinge on L&F? For the record, I am on a Windows 7 machine. I have tried setting the LayoutManager on the JMenuItem objects to BorderLayout:
cutMenuItem.setLayout(new BorderLayout(5,0));
Expecting to see a horizontal gap between the icon and text, but that seemed to make no 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);
}
}
Upvotes: 3
Views: 3155
Reputation: 47608
If you simply set the L&F to the system L&F on Windows 7, you have the desired effect:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Or do you want this on all platforms/L&F ?
Upvotes: 3