Swing从容器中删除组件并重新绘制

Lui*_*rno 1 java swing jtree mouselistener

我已经实现了一个扩展JTree的导航树.对于节点上的每次单击,在删除上一个表单后,将显示节点提供的表单.

如果节点未提供任何表单,则只需移动旧表单.

我的问题是显示第一个表单的部分有效,但是当我点击没有表单的节点(null)时,旧表单仍然显示,直到我调整窗口大小.

这是我的代码:

public class NavigationTree extends EncoTree {

private Container target = null;

public NavigationTree(Color from, Color to, Container trg) {
    super(from, to);
    this.target = trg;

    this.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent me){
            TreePath tps = getSelectionPath();
            if(tps != null){
                cstmMutableTreeNode node = (cstmMutableTreeNode) getLastSelectedPathComponent();
                target.removeAll();     
                if(node.form != null){
                    node.form.construct();
                    node.form.setPreferredSize(new Dimension(200, target.getSize().height));

                    target.add(node.form, BorderLayout.PAGE_START);

                }
                target.validate();
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

}

据我了解,repaint()只要我重新验证容器,就应该在EDT中将请求排入队列.

那么,为什么显示第一个表单而不必调整窗口大小,只是删除组件不?

cam*_*ckr 6

据我所知,只要我重新验证容器,就应该在EDT中将repaint()请求排入队列.

使用Swing时,您应该在目标容器上使用revalidate()(而不是验证)repaint().重绘可能不会自行发生,因为它听起来像是用相同大小的组件替换现有组件,因此Swing认为没有任何改变并且不进行重绘.