编程语言
首页 > 编程语言> > Java-一次调用repaint()方法,然后不显示任何内容

Java-一次调用repaint()方法,然后不显示任何内容

作者:互联网

我一直在尝试绘制n元树状结构的图形,因此当我输入某个节点时,它会显示出来,但事实并非如此.

它仅绘制根,然后“删除”所有内容.

这是我的代码:

public LinkedList<Node> nodes;
public Tree tree;

public TreeViewer() {

    initComponents();
    this.nodes = new LinkedList<>();
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.

    if (this.tree != null) {
        this.checkTree(this.tree.getRoot(), g, 200, 20, 20, 20);
    }else{
        System.out.println("empty");
    }
}

public void checkTree(Node current, Graphics g, int x, int y, int height, int width) {

    current.setX(x);
    current.setY(y);
    current.setHeight(height);
    current.setWidth(width);

    if (!this.nodes.contains(current)) {
        g.drawString(current.name, x, y);
        g.setColor(Color.black);
        this.nodes.add(current);

        if (current.getSon() != null && current.getBrother() == null) {
            this.checkTree(current.getSon(), g, x, y + 40, height, width);

        } else if (current.getBrother() != null && current.getSon() == null) {
            this.checkTree(current.getBrother(), g, x - 30, y, height, width);

        } else if (current.getBrother() != null && current.getSon() != null) {
            this.checkTree(current.getSon(), g, x, y + 40, height, width);
            this.checkTree(current.getBrother(), g, x - 30, y, height, width);
        }
    }
}

我在节点上添加了一个按钮,下面是代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if(this.modificator.getTree() == null){
        Node current = new Node(JOptionPane.showInputDialog("Type root ID:"));
        this.modificator.setTree( new Tree(current));

    }else{
        Node current = new Node(JOptionPane.showInputDialog("Type ID:"));
        this.modificator.getTree().addSon(this.modificator.getTree().getRoot(), this.modificator.getTree().getRoot(), current);

    }
    this.modificator.repaint();
}

因此,我的问题仍然出在我第一次调用repaint()之后,所有绘制的内容(仅根目录)都从面板中“擦除”了.

解决方法:

在checkTree内部,您有以下内容:

if (!this.nodes.contains(current))

大概是为了处理图中的循环,但是我看不到任何清除this.nodes的地方.这意味着在第二次调用paintComponent时,您立即退出了CheckTree,因为根已经添加到了this.nodes中.

如果清除paintComponent末尾的this.nodes可能会成功.

标签:repaint,swing,java
来源: https://codeday.me/bug/20191118/2031337.html