Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

public class Main extends JFrame {
    public static void main(String[] args) {
        new Main(5);
    }

    public Main(int n) {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container content = getContentPane();
        JTree tree = new JTree(new OutlineNode(1, n));
        content.add(new JScrollPane(tree), BorderLayout.CENTER);
        setSize(300, 475);
        setVisible(true);
    }
}

class OutlineNode extends DefaultMutableTreeNode {
    boolean areChildrenDefined = false;
    int outlineNum;
    int numChildren;

    public OutlineNode(int outlineNum, int numChildren) {
        this.outlineNum = outlineNum;
        this.numChildren = numChildren;
    }

    @Override
    public boolean isLeaf() {
        return false;
    }

    @Override
    public int getChildCount() {
        if (!areChildrenDefined) {
            defineChildNodes();
        }
        return super.getChildCount();
    }

    private void defineChildNodes() {
        areChildrenDefined = true;
        for (int i = 0; i < numChildren; i++) {
            add(new OutlineNode(i + 1, numChildren));
        }
    }

    @Override
    public String toString() {
        TreeNode parent = getParent();
        if (parent == null) {
            return String.valueOf(outlineNum);
        } else {
            return parent.toString() + "." + outlineNum;
        }
    }
}