1 20 21 26 27 package edu.umd.cs.findbugs.gui; 28 29 import java.awt.FlowLayout ; 30 import java.awt.event.KeyEvent ; 31 32 import javax.swing.JButton ; 33 import javax.swing.JFrame ; 34 35 import edu.umd.cs.findbugs.SystemProperties; 36 37 44 public class AnnotatedString { 45 46 private static final boolean MAC_OS_X = 47 SystemProperties.getProperty("os.name").toLowerCase().startsWith("mac os x"); 48 49 private final String myAnnotatedString; 50 51 public AnnotatedString(String s) { 52 myAnnotatedString = s; 53 } 54 55 58 @Override 59 public String toString() { 60 if (MAC_OS_X) { 61 if (myAnnotatedString.matches("[^&]+\\(&\\p{Alnum}\\)")) { 63 int endIndex = myAnnotatedString.length() - "(&X)".length(); 64 65 return myAnnotatedString.substring(0, endIndex); 66 } 67 68 if (myAnnotatedString.matches("[^&]+\\(&\\p{Alnum}\\)\\.\\.\\.")) { 70 int startIndex = myAnnotatedString.length() - "(&X)...".length(); 71 int endIndex = startIndex + "(&X)".length(); 72 73 return new StringBuffer (myAnnotatedString).delete(startIndex, endIndex).toString(); 74 } 75 } 76 return myAnnotatedString.replaceFirst("&", ""); 77 } 78 79 86 public int getMnemonic() { 87 int mnemonic = KeyEvent.VK_UNDEFINED; 88 if (!MAC_OS_X) { 89 int index = getMnemonicIndex(); 90 if ((index >= 0) && ((index + 1) < myAnnotatedString.length())) { 91 mnemonic = Character.toUpperCase(myAnnotatedString.charAt(index + 1)); 92 } 93 } 94 return mnemonic; 95 } 96 97 101 public int getMnemonicIndex() { 102 int index = -1; 103 if (!MAC_OS_X) { 104 index = myAnnotatedString.indexOf('&'); 105 if (index + 1 >= myAnnotatedString.length()) { 106 index = -1; 107 } 108 } 109 return index; 110 } 111 112 113 116 private static void addButton(JFrame frame, String s) { 117 AnnotatedString as = new AnnotatedString(s); 118 JButton button = new JButton (as.toString()); 119 button.setMnemonic(as.getMnemonic()); 120 button.setDisplayedMnemonicIndex(as.getMnemonicIndex()); 121 frame.getContentPane().add(button); 122 123 System.out.println("\"" + s + "\" \"" + as + "\" '" + 124 as.getMnemonic() + "' " + as.getMnemonicIndex()); 125 } 126 127 public static void main(String [] args) { 128 130 JFrame frame = new JFrame (); 131 frame.getContentPane().setLayout(new FlowLayout ()); 132 133 addButton(frame, "&File"); 134 addButton(frame, "S&ave As..."); 135 addButton(frame, "Save &As..."); 136 addButton(frame, "Fo&o"); 137 addButton(frame, "Foo"); 138 139 addButton(frame, ""); 141 addButton(frame, "&"); 142 addButton(frame, "Foo&"); 143 addButton(frame, "Cat & Dog"); 144 addButton(frame, "Cat && Dog"); 145 146 frame.pack(); 147 frame.setVisible(true); 148 } 149 150 } 151 | Popular Tags |