MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class MainClass extends JFrame {
    private JTree tree1;

    private JLabel showName = new JLabel();

    public static void main(String[] args) {
        new MainClass();
    }

    public MainClass() {
        this.setSize(225, 325);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel1 = new JPanel();

        DefaultMutableTreeNode root, a, b, c, d, e;

        root = new DefaultMutableTreeNode("A");

        a = makeShow("B", root);
        makeShow("C", a);
        makeShow("D", a);

        b = makeShow("E", root);
        d = makeShow("F", b);
        makeShow("G", d);
        e = makeShow("H", b);
        makeShow("I", e);
        makeShow("J", b);
        makeShow("K", b);

        c = makeShow("L", root);
        makeShow("M", c);
        makeShow("N", c);
        makeShow("O", c);

        tree1 = new JTree(root);
        tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree1.setVisibleRowCount(12);
        tree1.addTreeSelectionListener(new TreeListener());

        JScrollPane scroll = new JScrollPane(tree1);
        panel1.add(scroll);

        panel1.add(showName);
        this.add(panel1);
        this.setVisible(true);
    }

    private DefaultMutableTreeNode makeShow(String title, DefaultMutableTreeNode parent) {
        DefaultMutableTreeNode show;
        show = new DefaultMutableTreeNode(title);
        parent.add(show);
        return show;
    }

    private class TreeListener implements TreeSelectionListener {
        public void valueChanged(TreeSelectionEvent e) {
            Object o = tree1.getLastSelectedPathComponent();
            DefaultMutableTreeNode show = (DefaultMutableTreeNode) o;
            String title = (String) show.getUserObject();
            showName.setText(title);
        }
    }
}