Java Swing OSX Window Window Alignment

Java Swing seems to put β€œMenu Text” after the icon (if present) in MenuItems. See the example below.

Window Menu on OSX

It doesn’t look very good.

Is there any way around this?

In OSX, the icon is in the left margin, and the text aligns with all other MenuItems.

0
source share
2 answers

You mean something like this:

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextPaneExample { private Icon info = UIManager.getIcon("OptionPane.informationIcon"); private Icon error = UIManager.getIcon("OptionPane.errorIcon"); private void createAndDisplayGUI() { JFrame frame = new JFrame("JTextPane Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextPane tpane = new JTextPane(); tpane.setContentType("text/html"); JScrollPane scroller = new JScrollPane(); scroller.setViewportView(tpane); try { java.net.URL url = new java.net.URL("http://maps.google.es/"); //tpane.setPage(url); } catch (Exception e) { e.printStackTrace(); } frame.setJMenuBar(createMenuBar()); frame.getContentPane().add(scroller); frame.setSize(300, 300); frame.setVisible(true); } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu windowMenu = new JMenu("Window"); JMenuItem minimizeItem = new JMenuItem("Minimize"); minimizeItem.setMargin(new java.awt.Insets(0, 10, 0, 0)); minimizeItem.setIcon(info); minimizeItem.setIconTextGap(1); minimizeItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); JMenuItem zoomItem = new JMenuItem("Zoom"); zoomItem.setMargin(new java.awt.Insets(0, 10, 0, 0)); zoomItem.setIconTextGap(1); zoomItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Check Me", null, true); cbmi.setMargin(new java.awt.Insets(5, 25, 5, 5)); cbmi.setIconTextGap(17); cbmi.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); windowMenu.add(minimizeItem); windowMenu.add(zoomItem); windowMenu.add(cbmi); menuBar.add(windowMenu); return menuBar; } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new JTextPaneExample().createAndDisplayGUI(); } }); } } 

Here is the result:

MENUITEM

+2
source

You can try any of these approaches:

  • Unicode characters are attractive, but they offer poor alignment in variable pitch fonts:

     JMenuBar menuBar = new JMenuBar(); JMenu windowMenu = new JMenu("Window"); windowMenu.add(new JMenuItem("♦ Item")); windowMenu.add(new JMenuItem("βœ“ Item")); windowMenu.add(new JMenuItem("β€’ Item")); menuBar.add(windowMenu); frame.setJMenuBar(menuBar); 
  • Better implement the Icon interface, illustrated here and here , using a fixed size to control the geometry. CellTest shows one approach to displaying an arbitrary Unicode character.

+2
source

All Articles