1 21 22 package org.armedbear.j; 23 24 import java.awt.Color ; 25 import java.awt.Dimension ; 26 import java.awt.Font ; 27 import java.awt.FontMetrics ; 28 import java.awt.Graphics ; 29 import java.awt.Insets ; 30 import java.awt.event.KeyEvent ; 31 import javax.swing.JMenuItem ; 32 import javax.swing.MenuElement ; 33 import javax.swing.MenuSelectionManager ; 34 import javax.swing.UIManager ; 35 36 public final class MenuItem extends JMenuItem 37 { 38 private static final Font acceleratorFont = 39 UIManager.getFont("MenuItem.acceleratorFont"); 40 private static final Color acceleratorForeground = 41 UIManager.getColor("MenuItem.acceleratorForeground"); 42 private static final Color acceleratorSelectionForeground = 43 UIManager.getColor("MenuItem.acceleratorSelectionForeground"); 44 private static final Color disabledForeground = 45 UIManager.getColor("MenuItem.disabledForeground"); 46 47 private final String acceleratorText; 48 49 public MenuItem(String label, String acceleratorText) 50 { 51 super(label); 52 this.acceleratorText = acceleratorText; 53 } 54 55 public Dimension getPreferredSize() 56 { 57 Dimension d = super.getPreferredSize(); 58 if (acceleratorText != null) 59 d.width += getToolkit().getFontMetrics(acceleratorFont).stringWidth(acceleratorText) + 30; 60 return d; 61 } 62 63 public void paint(Graphics g) 66 { 67 Display.setRenderingHints(g); 68 super.paint(g); 69 if (acceleratorText != null) { 70 g.setFont(acceleratorFont); 71 Color c; 72 if (isEnabled()) 73 c = getModel().isArmed() ? acceleratorSelectionForeground : acceleratorForeground; 74 else 75 c = disabledForeground; 76 g.setColor(c); 77 FontMetrics fm = g.getFontMetrics(); 78 Insets insets = getInsets(); 79 g.drawString(acceleratorText, 80 getWidth() - (fm.stringWidth(acceleratorText) + insets.right + insets.left), 81 getFont().getSize() + (insets.top - 1)); 82 } 83 } 84 85 private static final boolean consumeKeyEvent = 86 Platform.isJava13() || Platform.isJava140(); 87 88 public void processKeyEvent(KeyEvent e, MenuElement path[], MenuSelectionManager manager) 89 { 90 super.processKeyEvent(e, path, manager); 91 if (consumeKeyEvent) 92 if (Character.toUpperCase(e.getKeyChar()) == getMnemonic()) 93 e.consume(); 94 } 95 } 96 | Popular Tags |