【问题标题】:JTree key bindingsJTree 键绑定
【发布时间】:2020-01-22 08:01:50
【问题描述】:

我正在尝试为 JTree 重新绑定 F2 键,如此处所述https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html。代码如下:


System.out.println(DataModelTree.getInputMap(JComponent.WHEN_FOCUSED).get(KeyStroke.getKeyStroke("F2")));
//This gives string "startEditing"

DataModelTree.getActionMap().put("startEditing", new javax.swing.AbstractAction() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
        System.out.println("F2 pressed");
    }
});

也试过这个变种:

DataModelTree.getActionMap().put(DataModelTree.getInputMap(JComponent.WHEN_FOCUSED).get(KeyStroke.getKeyStroke("F2")), new javax.swing.AbstractAction() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
         System.out.println("F2 pressed");
    }
});

尝试创建单独的非匿名操作类。尝试初步删除 InputMap 和父 InputMap 中的条目。尝试在其他模式下重新绑定:WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 和 WHEN_IN_FOCUSED_WINDOW。没有任何效果。 JTree 键绑定保持不变。

请帮忙。

【问题讨论】:

    标签: java swing key-bindings jtree


    【解决方案1】:

    抱歉,我们无法回答您的问题,因为我们看不到您的完整代码。请提供runnable class,重现您的错误行为,以便我们更容易确定您的错误在哪里。

    这是一个小例子,如何为 F2 键提供树的编辑

    import java.awt.event.ActionEvent;
    
    import javax.swing.AbstractAction;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import javax.swing.WindowConstants;
    
    /**
     * <code>TestTree</code>.
     */
    public class TestTree {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new TestTree()::startUp);
        }
    
        private void startUp() {
            JTree tree = new JTree();
            tree.setEditable(true);
            tree.getActionMap().put(tree.getInputMap().get(KeyStroke.getKeyStroke("F2")), new AbstractAction() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (tree.getSelectionPath() != null) {
                        tree.startEditingAtPath(tree.getSelectionPath());
                    } else {
                        JOptionPane.showMessageDialog(tree, "Nothing selected");
                    }
                }
            });
            JFrame frm = new JFrame("edit tree");
            frm.add(new JScrollPane(tree));
            frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frm.setSize(300, 200);
            frm.setLocationRelativeTo(null);
            frm.setVisible(true);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多