2011-03-22 53 views
0

我扩展了BasicMenuUI,并覆盖了getPreferredSize(JComponent c),结果JMenu的文本不再居中了。JMenu的文本不居中

我试图用几个setAlignment方法修复它,但没有任何工作。

我想所有的菜单都有相同的尺寸,并且文字居中。

谢谢。

回答

0

BasicMenuItemUI继承的相关getPreferredSize()应该是“适合外观和感觉”。每个L & F使用不同大小的装饰。如果你不这样做,你应该返回null并指定“组件的布局管理器”。

当然,sscce会有所帮助。

附录:

的JMenu对象的文本不再居中。

我不认为它曾居中,但如果需要,您可以移动textRect

enter image description here

class CustomMenuUI extends BasicMenuUI { 

    public static ComponentUI createUI(JComponent c) { 
     return new CustomMenuUI(); 
    } 

    @Override 
    protected void paintText(Graphics g, JMenuItem menuItem, 
      Rectangle textRect, String text) { 
     g.setColor(Color.red); 
     int w2 = menuItem.getBounds().width/2; 
     textRect.translate(w2 - textRect.width/2, 0); 
     super.paintText(g, menuItem, textRect, text); 
    } 

    @Override 
    public Dimension getPreferredSize(JComponent c) { 
     return new Dimension(80, 32); 
    } 
} 
0
public class Main { 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      public void run() { 
       try { 
        UIManager.put("MenuUI", "testmenuui.CustomMenuUI"); 
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
         if ("Nimbus".equals(info.getName())) { 
          UIManager.setLookAndFeel(info.getClassName()); 
          break; 
         } 
        } 
        createAndShowGui(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    private static void createAndShowGui() { 
     JMenuBar menuBar = new JMenuBar(); 
     JMenu menuTest1 = new JMenu("Menu1"); 

     JMenu menuTest2 = new JMenu("Menu2"); 

     menuBar.add(menuTest1); 
     menuBar.add(menuTest2); 

     JFrame frame = new JFrame(); 
     frame.setJMenuBar(menuBar); 
     frame.setPreferredSize(new Dimension(800, 600)); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

class CustomMenuUI extends BasicMenuUI { 

    public static ComponentUI createUI(JComponent c) { 
     return new CustomMenuUI(); 
    } 

    @Override 
    protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { 
     g.setColor(Color.black); 
     super.paintBackground(g, menuItem, bgColor); 
    } 

    @Override 
    protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) { 
     g.setColor(Color.white); 
     super.paintText(g, menuItem, textRect, text); 
    } 

    @Override 
    public Dimension getPreferredSize(JComponent c) { 
     return new Dimension(100, 100); 
    } 
} 
+0

重新格式化的代码;如果不正确请回复。这应该是对你的问题的更新。 – trashgod 2011-03-23 01:36:25