【发布时间】:2014-07-10 19:24:37
【问题描述】:
我有一个向 jtree 添加问题的程序。 Jtree 上的每个问题都是 Question 类型,具有 3 个属性;名称、ID 和问题文本。我希望我的jtree仅显示问题名称,但选择节点时,它应该在文本框中显示QuestText。
问题是 Jtree 按我的意愿显示问题的名称,但是当我选择树的一个节点时,我得到一个 ClassCastException。这是因为我的 treeSelectionListener 方法中的 getUserObject() 。它获取 getUserObject() 返回的字符串并尝试将其转换为 Question 类。如何在没有 getUserObject() 的情况下获取所选字符串的 Question 类属性,例如 questionText 或 id,或者是否有另一种方式来表示这棵树?
这是我的代码:
public class Question
{
public String name;
public String id;
public String qText;
public Question(String name,String id, String text)
{
this.name = name;
this.id = id;
this.qText = text;
}
public String getQuestion()
{ return qText; }
public String getName()
{ return name;}
public String getId()
{ return id;}
public void setQuestionText(String text)
{ qText= text; }
public void setId(String uid)
{ id = uid;}
@Override
public String toString()
{ return name; }
}
创建树的部分代码:
public Question rootQ = new Question("Questions", UUID.randomUUID().toString(), "What is your name?");
public DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootQ.toString());
public JTree tree = new JTree(rootNode);
initialise(){
//....other code to initilise
panel.add(new JScrollPane(tree));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
tree.addTreeSelectionListener(treeMenuClicked);
tree.setRootVisible(true);
tree.setVisible(true);
panel.add(addChild());
}
public TreeSelectionListener treeMenuClicked = new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
TreePath currentSelection = tree.getSelectionPath();
if(currentSelection != null){
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)currentSelection.getLastPathComponent();
Object nodeInfo = currentNode.getUserObject();
Question questionText = (Question)nodeInfo;
txtQuestion.setText(questionText.getQuestion());
}
}};
public JButton addChild()
{
JButton btnAddChild = new JButton("Add Child");
btnAddChild.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{ String userQuestion = txtQuestion.getText();
TreePath currentSelection = tree.getSelectionPath();
if (currentSelection != null) {
Question createdQuestion = new Question(userQuestion,UUID.randomUUID().toString(),userQuestion);
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) currentSelection.getLastPathComponent();
DefaultTreeModel model = ((DefaultTreeModel) tree.getModel());
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(createdQuestion.toString());
currentNode.add(newNode);
model.nodeStructureChanged(currentNode);
}
}});
btnAddChild.setBounds(609, 374, 117, 47);
return btnAddChild;
}
【问题讨论】:
-
您似乎将字符串 (
rootQ.toString()) 作为DefaultMutableTreeNode的参数传递。请仅使用rootQ作为构造函数参数,因为您需要从中“获取” qText。 -
@Ajay 我在没有 toString 的情况下尝试过这个,发现它返回树上的整个对象属性。所以我树上的一个节点会有名字、id和问题