OSX上的Java:使用Netbeans GUI构建器的Swing菜单中的加速键错误图标 [英] Java on OSX: wrong accelerator key icon in Swing menu using Netbeans GUI builder
问题描述
我在OSX上使用Netbeans 8.1创建了一个小型应用程序.它仅包含两个菜单文件"和编辑".目的是稍后向编辑菜单添加完整的复制/剪切/粘贴功能.我想使用Netbeans GUI构建器,但是遇到以下问题:
I created a small application using Netbeans 8.1 on OSX. It contains just two menus "file" and "edit". The purpose is to add full copy / cut / paste functionality to the edit menu later on. I want to use Netbeans GUI builder but i encounter the following problems:
第一次尝试:
我使用Netbeans GUI构建器创建了一个小示例(Swing GUI Forms-> JDialog).我刚刚在JFrame中添加了一个菜单栏,并在GUI构建器中添加了JMenuItem,并向构造函数添加了一些代码. 结果是:
I created a small example with Netbeans GUI builder (Swing GUI Forms -> JDialog). I just added a menu bar to the JFrame and the a JMenuItem in the GUI builder and some code to the constructor. The result is:
如您所见,我得到的是文本元"而不是Apple键⌘".
As you can see i get a text 'meta' instead of the Apple key '⌘'.
源代码为NewJDialogGUI.java
:
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
public class NewJDialogGUI extends javax.swing.JDialog {
private static final int MASK
= Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
public NewJDialogGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
AbstractAction copyAction = new DefaultEditorKit.CopyAction();
copyAction.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));
this.jMenuItem1.setAction(copyAction);
this.jMenuItem1.setText("Copy");
this.jMenuItem1.setMnemonic(KeyEvent.VK_C);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuItem1.setText("jMenuItem1");
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 278, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJDialogGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJDialogGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJDialogGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJDialogGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialogGUI dialog = new NewJDialogGUI(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
}
和NewJDialogGUI.form
:
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
<NonVisualComponents>
<Menu class="javax.swing.JMenuBar" name="jMenuBar1">
<SubComponents>
<Menu class="javax.swing.JMenu" name="jMenu1">
<Properties>
<Property name="text" type="java.lang.String" value="File"/>
</Properties>
</Menu>
<Menu class="javax.swing.JMenu" name="jMenu2">
<Properties>
<Property name="text" type="java.lang.String" value="Edit"/>
</Properties>
<SubComponents>
<MenuItem class="javax.swing.JMenuItem" name="jMenuItem1">
<Properties>
<Property name="text" type="java.lang.String" value="jMenuItem1"/>
</Properties>
</MenuItem>
</SubComponents>
</Menu>
</SubComponents>
</Menu>
</NonVisualComponents>
<Properties>
<Property name="defaultCloseOperation" type="int" value="2"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="menuBar" type="java.lang.String" value="jMenuBar1"/>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="400" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="278" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
</Form>
第二次尝试:
我用Netbeans GUI构建器创建了另一个小示例(Swing GUI Forms-> Application sample form).结果是:
I created another small example with Netbeans GUI builder (Swing GUI Forms -> Application sample form). The result is:
与第一次尝试相同的结果.
Same result like in 1st try.
第三次尝试:
最后,我创建了一个使用Netbeans(空Java文件)的示例,其源代码从此处进行了略微修改.结果是:
Finally i created an example with Netbeans (Empty Java file) with source code slightly modified from here. The result is:
源代码为:
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
/**
* @see https://stackoverflow.com/a/34830519/230513
*/
public class NewEmptyGUI {
private static final int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Edit");
menu.setMnemonic(KeyEvent.VK_E);
JMenuItem menuItem = new JMenuItem();
AbstractAction copyAction = new DefaultEditorKit.CopyAction();
copyAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));
menuItem.setAction(copyAction);
menuItem.setText("Copy");
menu.add(menuItem);
menuBar.add(menu);
f.setJMenuBar(menuBar);
f.add(new JTextField(10));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NewEmptyGUI().display();
}
});
}
}
这是预期的结果,但是整个菜单基础结构都是手动编码的,这不是我的意图.我想使用Netbeans GUI Builder.你对我有什么提示吗?
This is the expected result but the whole menu infrastrucure was coded manually, which is not my intention. I want to use Netbeans GUI Builder. Do you have any hints for me?
我正在使用JDK7和OSX Yosemite.外观是雨云".我只粘贴示例代码,或者在此处粘贴第1和第3次尝试,因为它包含很多代码.
I am using JDK7 and OSX Yosemite. Look and feel is "Nimbus". I only paste the example code or 1st and 3rd try here, because it is quite a lot of code.
推荐答案
我找到了上述问题的解决方案.
I found solutions for the described problem.
解决方案1(更改外观):
该代码示例演示如何替换Netbeans创建的代码中的"Nimbus外观".它还会为剪贴板操作(例如复制和设置)设置正确的键盘快捷键.自动粘贴Apple键⌘"而不是"Control-Key":
The code example shows how to replace the "Nimbus look and feel" in the Netbeans created code. It will also set the correct keyboard shortcuts for clipboard actions like copy & paste with Apple key '⌘' instead of the "Control-Key" automatically:
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
/*
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
*/
if ("Mac OS X".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(App_Avaprism.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(App_Avaprism.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(App_Avaprism.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(App_Avaprism.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new App_Avaprism().setVisible(true);
}
});
解决方案2:
如果您想呆在雨云台"上,事情会变得更加困难.一开始:我发现没有办法替换文本元".至少您可能想让剪贴板快捷方式与Apple键⌘"一起使用.
If you want to stay with "Nimbus" things become more difficult. At first: I found no way to replace text 'meta'. At least you might want to have the clipboard shortcuts working with the Apple key '⌘'.
对于您的主应用程序,将以下代码放入构造函数中:
For your main application put the following code into the constructor:
int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK), DefaultEditorKit.copyAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, MASK), DefaultEditorKit.pasteAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, MASK), DefaultEditorKit.cutAction);
不幸的是:如果您从此主应用程序启动其他模式对话框,则快捷方式将不起作用.在这种情况下,您可以尝试使用KeyEventDispatcher为整个应用程序建立击键的全局重定向.可以在此处和
Unfortunately: If you start other modal dialogs from this main app the short cuts won't work. In this case you may try to use the KeyEventDispatcher to establish a global redirection of keystrokes for the whole app. More information about that can be found here and here.
这篇关于OSX上的Java:使用Netbeans GUI构建器的Swing菜单中的加速键错误图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!