我扩展了BasicMenuUI,并覆盖了getPreferredSize(JComponent c),因此JMenu的文本不再居中。
我试着用几个setAlignment方法来修复它,但是都不起作用。
我想有相同的大小为所有的菜单,和文本居中。
谢谢。
发布于 2011-03-23 07:06:36
继承自BasicMenuItemUI的相关getPreferredSize()应该“适合于外观”。每个L&F使用不同大小的装饰品。如果您没有这样做,您应该返回null并指定“组件的布局管理器”。
当然,sscce会有所帮助。
附录:
JMenu的文本不再居中。
我不认为它曾经居中,但如果需要,您可以移动textRect。

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);
}
}发布于 2011-03-23 07:54:12
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);
}
}https://stackoverflow.com/questions/5396991
复制相似问题