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:

Current look of menu items

Interestingly, I noticed that the look of the JMenu components matches the look I want:

enter image description here

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);
    }

}

      

+3


source to share


1 answer


If you just set L&F to L&F system in Windows 7, you get the desired effect:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

      



Or do you want it on all platforms / L&F?

+3


source







All Articles