這是後續問題my previous post。我正在嘗試使用以下代碼將JTree放入JScrollPane中。 JTree的初始化看起來很好,在JTextField中輸入100之後,然後回車也很順利。但是當我滾動垂直滑動窗口,調整窗口大小時,或試圖擴展新的JTree節點時,我發現樹只有10個節點回到原始狀態。感謝你的幫助。替換JScrollPane中的JTree後發生的奇怪行爲
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class RandomJTree2 extends JFrame {
private final JTextField jtf = new JTextField(10);
private JTree tree;
JScrollPane jsp;
private Random generator = new Random();
private JTree buildTree(int nnodes) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(0);
DefaultMutableTreeNode cnode = node;
for (int i = 1; i <= nnodes; i++) {
System.out.println(i);
DefaultMutableTreeNode newn = new DefaultMutableTreeNode(i);
int j = generator.nextInt(2);
System.out.println("j=" + j);
if (j == 0 && i != 1) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)cnode.getParent();
if (parent != null) {
parent.add(newn);
cnode = parent;
} else {
node.add(newn);
cnode = newn;
}
} else {
cnode.add(newn);
cnode = newn;
}
}
return new JTree(node);
}
public RandomJTree2() {
setLayout(new BorderLayout());
add(jtf, BorderLayout.NORTH);
tree = buildTree(10);
jsp = new JScrollPane(tree);
add(jsp, BorderLayout.CENTER);
jtf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
invalidate();
// jsp.remove(tree);
// tree = buildTree(Integer.parseInt(jtf.getText()));
// jsp.add(tree);
// remove(jsp);
tree = buildTree(Integer.parseInt(jtf.getText()));
jsp = new JScrollPane(tree);
add(jsp, BorderLayout.CENTER);
validate();
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
public static void main(String[] args) {
new RandomJTree2();
}
}
謝謝!我以爲我嘗試過,但沒有奏效。無論如何,它現在工作正常。 :) –
重新驗證()+重繪(),以防止任何可能的問題與Swing重繪+1 – mKorbel
@mKorbel:你是說我不需要添加和刪除,只是重新驗證並重新繪製就足夠了? –