我希望以格式获取JTree的文本:
当我点击叶子时,我在JPanel中留下了信息
答案 0 :(得分:2)
这是一个简单的例子:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
public class TestFrame extends JFrame {
private JLabel lbl;
private JTree tree;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
tree = new JTree();
tree.getSelectionModel().addTreeSelectionListener(getListener());
lbl = new JLabel("empty");
add(new JScrollPane(tree));
add(lbl,BorderLayout.EAST);
}
private TreeSelectionListener getListener() {
return new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
lbl.setText(node == null ? "empty" : node.toString());
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}
在tutorial中阅读更多内容。