我有一个JTree和一个JtextField,所以我在文本字段中添加了侦听器,这样,如果我按Enter键,该节点将使用在该字段中输入的名称进行更新。
这很好,当我使用自定义的DefaultTreeCellRenderer渲染禁用的节点时会出现问题。此后,我必须手动单击该节点以查看更改的出现。
我确实尝试过reload(),nodeChanged(),但没有任何变化。
JTree面板:
public class RuleTree extends JPanel {
private static JTree autoscoreRuleTree;
private static DefaultTreeModel treeModel;
renameRule(){
/*
Code given below
*/
}
newRule(){
/*
Creates a new rule
*/
}
copyRule(){
/*
Copies a rule
*/
}
disableRule(){
/*
disables a rule codee given below
*/
}
文本字段类:
public class RuleNamePanel extends JPanel {
private static JLabel ruleName;
private static JTextField ruleNameTextField;
/* To rename on pressing enter*/
ruleNameTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
RuleTree.renameRule(ruleNameTextField.getText());
}
}
});
渲染类:(规则是自定义类)
public class AutoScoreRuleTreeRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean exp, boolean leaf,
int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
Rule rule = (Rule) ((DefaultMutableTreeNode) value).getUserObject();
this.setEnabled(rule.isActivated());
return this;
}
}
当我在文本字段上按Enter键时,就会调用此名称
public static void renameRule(String name) {
TreePath nodeToRename = autoscoreRuleTree.getSelectionPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeToRename.getLastPathComponent();
Rule rule = (Rule) node.getUserObject();
rule.setName(name);
treeModel.nodeChanged(node);
}
按钮面板
public class RuleModifyButtonPanel extends JPanel {
private JButton newRuleButton;
private JButton newChildButton;
private JButton duplicateRuleButton;
private JButton cutRuleButton;
private JButton pasteRuleButton;
private JButton disableRuleButton;
/*
Each button calls a method when clicked
*/
//When disable button is pressed this will internally call enableNode method
disableRuleButton.addActionListener(e -> RuleTree.disableRule());
}
禁用节点方法
private static void enableNodes(DefaultMutableTreeNode node, boolean enable) {
autoscoreRuleTree.setCellRenderer(new AutoScoreRuleTreeRenderer());
enablePanels(enable);
Rule rule = (Rule) node.getUserObject();
}
预期会在输入时更改,但是当我手动单击树时会更改。
在使用渲染之前: Enter the name> Pressed Enter
使用渲染后: Enter the name after render> Press Enter> Click manually