我正在尝试为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的键绑定保持不变。
请帮助。
[抱歉,我们无法回答您的问题,因为我们看不到您的完整代码。请提供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);
}
}