gpt4 book ai didi

java - 虚拟键盘与 Nimbus 冲突

转载 作者:行者123 更新时间:2023-11-29 05:40:15 25 4
gpt4 key购买 nike

我想知道为什么 Nimbus会以某种方式与 Virtual keys 发生冲突.查看我在下面制作的示例:

    public class buttontest implements ActionListener {

JMenuItem close =new JMenuItem("Close");

public static void main (String[] args){

try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}

}

public buttontest(){

JFrame test = new JFrame();
JMenuBar bar=new JMenuBar();
JMenu file=new JMenu("File");

close.setMnemonic(KeyEvent.VK_C);
file.setMnemonic(KeyEvent.VK_F);

test.setExtendedState(test.getExtendedState() | test.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize())
test.setDefaultCloseOperation(1);

bar.add(file);
file.add(close);
test.setJMenuBar(bar);
test.setVisible(true);
}

public void actionPerformed(ActionEvent e){

if(e.getSource()==close){
System.exit(0);
}
}

}

按照它写的方式,你可以尝试使用Virtual keys。您会看到 Alt F 可以打开"file"菜单,但 Alt C 不会关闭应用程序。换句话说,如果您注释 Nimbus 代码,两个虚拟键都将起作用。

我对这个“错误”进行了一项研究(或者我可能做错了我不知道)但直到现在我一无所获。有没有人通过这个?

最佳答案

您必须为 JMenuItem 使用 setAccelerator() 方法:

close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK ));

来自 Javadoc:
JMenuItem#setAccelerator(KeyStroke)

Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy. It is the UI's responsibility to install the correct action. Note that when the keyboard accelerator is typed, it will work whether or not the menu is currently displayed.


补充说明:

  1. LookAndFeelInfo 替换为 UIManager.LookAndFeelInfo,因为它是 UIManager 中的内部类。

  2. main 方法中调用构造函数。

  3. setDefaultCloseOperation(1) 的参数更改为 3 作为 3 = JFrame.EXIT_ON_CLOSE,但是 1=JFrame.HIDE_ON_CLOSE隐藏框架,就我个人而言,我讨厌它,因为为关闭框架创建的关闭按钮,隐藏它,就像Skype。

  4. actionListener添加到关闭按钮:close.addActionListener(this);

关于java - 虚拟键盘与 Nimbus 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17885242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com