问题描述
package com.hello.model;import java.util.concurrent.TimeUnit;import javax.swing.*;import javax.swing.tree.*;public class NewTree {JFrame frame = new JFrame();DefaultMutableTreeNode parent = new DefaultMutableTreeNode("baidu");DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("sohu");DefaultMutableTreeNode child11 = new DefaultMutableTreeNode("sina");DefaultMutableTreeNode child12 = new DefaultMutableTreeNode("taobao");DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("163");JTree tree = new JTree(parent);private void init() throws InterruptedException {parent.add(child1);parent.add(child2);child1.add(child11);child1.add(child12);tree.expandPath(new TreePath(child1.getPath()));frame.add(new JScrollPane(tree));frame.pack();frame.setVisible(true);TimeUnit.SECONDS.sleep(5);child1.remove(child11); //tree.updateUI(); //1处代码可以更新UItree.repaint(); //2处代码无法更新UI}public static void main(String[] args) throws InterruptedException {new NewTree().init();}}为什么1处代码可以更新UI,能够看到节点删除的效果,而2处就不可以?
解决方案
updateUI()通常当look and feel发生变化时调用,从UIManager中获取新的L&F,应用到组件上,重绘的范围比较大,要稍微慢一些。repaint()只是通知RepaintManager重绘组件,不包括UI和布局的管理。