在 Windows XP 上运行的 Java Swing 应用程序中,我无法让下划线始终显示在上下文菜单上的助记符上。
如果我右击鼠标,下划线不会出现在弹出菜单上——这很好,因为这种行为与其他 Windows 应用程序一致。
但是,如果使用菜单键(通常在右 Windows 键旁边)调出弹出菜单,下划线不会出现在我的 Swing 应用程序中,而它们会出现在标准的 Windows 应用程序中,例如写字板、资源管理器和控制面板。
让下划线显示的唯一方法是在按住 Alt 键的同时右键单击鼠标。这有点没用,因为如果有人已经将手放在鼠标上进行右键单击,他们将不想使用键盘在弹出窗口中选择某些内容。
当从菜单键调用上下文菜单时,是否可以在 Swing 中显示下划线?没有编写我自己的外观和感觉库?
最佳答案
好问题。我刚刚在 OS X 上试过这个,但我也没有得到带下划线的字母。就像你一样,我通过按下 alt 按钮来获取它们(不是在单击期间,而是在显示我的弹出菜单时)。
但是,在 OS X 上,我不记得任何包含下划线字母的弹出窗口。我刚刚检查了一些默认应用程序,它们都没有带下划线项目的弹出菜单。快速谷歌搜索 indicated this as well .因此在这种情况下,外观与操作系统一致。
经过更多谷歌搜索,我找到了 following topic这表明在 Windows 中有一个选项可以默认隐藏助记符,并且仅在您按下 alt 时显示它们(如果我在 windows 时代没记错的话,无论如何都需要按下才能使用助记符)。您可能想尝试一下。
无论如何,这里有一个 SSCCE 允许 Windows 用户快速测试它:
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class MnemonicTest {
public static JFrame createUI(){
JFrame testFrame = new JFrame( );
testFrame.add( createLabelWithPopupMenu() );
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
testFrame.pack();
return testFrame;
}
private static JLabel createLabelWithPopupMenu(){
JLabel result = new JLabel( "Right-click me" );
result.setComponentPopupMenu( createPopupMenu() );
return result;
}
private static JPopupMenu createPopupMenu(){
JPopupMenu popupMenu = new JPopupMenu( );
popupMenu.add( createAction() );
return popupMenu;
}
private static Action createAction(){
AbstractAction result = new AbstractAction() {
@Override
public void actionPerformed( ActionEvent e ) {
System.out.println( "MnemonicTest.actionPerformed" );
}
};
result.putValue( Action.MNEMONIC_KEY, KeyEvent.VK_A );
result.putValue( Action.NAME, "Action" );
return result;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
createUI().setVisible( true );
}
} );
}
}
关于swing - Windows XP 上的 Java Swing 弹出菜单上的助记符(带下划线的字母),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10377129/