1

我在 OSX 上使用 Netbeans 8.1 创建了一个小型应用程序。它只包含两个菜单“文件”和“编辑”。目的是稍后在编辑菜单中添加完整的复制/剪切/粘贴功能。我想使用 Netbeans GUI builder,但遇到以下问题:

第一次尝试:

我用 Netbeans GUI builder (Swing GUI Forms -> JDialog) 创建了一个小例子。我刚刚在 JFrame 中添加了一个菜单栏,在 GUI 构建器中添加了一个 JMenuItem,并在构造函数中添加了一些代码。结果是:

在此处输入图像描述

如您所见,我得到一个文本“元”而不是 Apple 键“⌘”。

源代码是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 builder 创建了另一个小例子(Swing GUI Forms -> Application sample form)。结果是:

在此处输入图像描述

与第一次尝试相同的结果。

第三次尝试:

最后,我使用 Netbeans(空 Java 文件)创建了一个示例,其源代码从此处稍作修改。结果是:

在此处输入图像描述

源代码是:

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。你对我有什么提示吗?

我正在使用 JDK7 和 OSX Yosemite。外观和感觉是“Nimbus”。我在这里只粘贴示例代码或第一次和第三次尝试,因为它的代码非常多。

4

1 回答 1

1

我找到了所描述问题的解决方案。

解决方案 1(更改外观):

该代码示例显示了如何替换 Netbeans 创建的代码中的“Nimbus 外观”。它还将为剪贴板操作设置正确的键盘快捷键,例如使用 Apple 键“⌘”而不是“Control-Key”自动复制和粘贴:

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 键“⌘”一起使用。

对于您的主应用程序,将以下代码放入构造函数中:

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 为整个应用程序建立击键的全局重定向。更多信息可以在这里这里找到。

于 2016-04-03T11:50:12.140 回答