2011-03-22 154 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