Monday, March 4, 2013

Dynamically Adding Panel Based on Tree items in JTabbedPane

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtabbedpanedemo;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author R.Amirtharaj
 */
public class MainFrame {

    private JTabbedPane tabbedPane;
    private static final Icon CLOSE_TAB_ICON = new ImageIcon("Image location");
    // Key as Panel Name and Value as Panel index
    static final HashMap hmPanel = new HashMap();
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create Tree . Panel1 an Panel2 under Root
     */
    public void createTreeComponents() {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode tp1 = new DefaultMutableTreeNode("Panel1");
        DefaultMutableTreeNode tp2 = new DefaultMutableTreeNode("Panel2");
        top.add(tp1);
        top.add(tp2);

        // Create a new tree control
        DefaultTreeModel treeModel = new DefaultTreeModel(top);
        jTree1.setModel(treeModel);


        jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        jTree1.addTreeSelectionListener(new TSL());
    }

    // Tree Selection Listioner
    public class TSL implements TreeSelectionListener {

        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

            if (node == null) //Nothing is selected.
            {
                return;
            }

            Object nodeInfo = node.getUserObject();
            if (node.isLeaf()) {
                if (node.toString().equals("Panel1")) {
                    if (!hmPanel.containsKey("Panel1")) {
                        int index = hmPanel.size();
                        hmPanel.put("Panel1", index);
                        JPanel pan = new JPanel();
                        pan.add(new JLabel("Panel1"));
                        pan.setToolTipText("Panel1");
                        addClosableTab(tabbedPane, pan, "Panel1", null);
                    } else {
                        //System.out.println(hmPanel.get("Panel1"));
                        tabbedPane.setSelectedIndex(hmPanel.get("Panel1"));
                    }

                } else if (node.toString().equals("Panel2")) {
                    if (!hmPanel.containsKey("Panel2")) {
                        int index = hmPanel.size();
                        hmPanel.put("Panel2", index);
                        JPanel pan = new JPanel();
                        pan.add(new JLabel("Panel2"));
                        pan.setToolTipText("Panel2");
                        addClosableTab(tabbedPane, pan, "Panel2", null);
                    } else {
                        //System.out.println(hmPanel.get("Panel2"));
                        tabbedPane.setSelectedIndex(hmPanel.get("Panel2"));
                    }
                }

            } else {
            }
        }
    }

    private static void createAndShowGUI() {
        //Create and set up the frame.
        //The string passed as an argument will be displayed
        //as the title.

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JTabbedPane Demo [=]");

        //Create and set up the content pane.
        MainFrame demo = new MainFrame();
        demo.addContentPane(frame.getContentPane());

        // The other bits and pieces that make our program a bit more stable.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public void addContentPane(Container container) {
        tabbedPane = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        createTreeComponents();

        container.add(tabbedPane, java.awt.BorderLayout.CENTER);

        jScrollPane1.setViewportView(jTree1);
        container.add(jScrollPane1, java.awt.BorderLayout.WEST);
    }

    /**
     * Adds a component to a JTabbedPane with a little "close tab" button on the
     * right side of the tab.
     * @param tabbedPane the JTabbedPane
     * @param c any JPanel
     * @param title the title for the tab
     * @param icon the icon for the tab, if desired
     */
    public static void addClosableTab(final JTabbedPane tabbedPane, final JPanel c, final String title,
            final Icon icon) {
        // Add the tab to the pane without any label
        tabbedPane.addTab(null, c);
        int pos = tabbedPane.indexOfComponent(c);

        // Create a FlowLayout that will space things 5px apart
        FlowLayout f = new FlowLayout(FlowLayout.CENTER, 5, 0);

        // Make a small JPanel with the layout and make it non-opaque
        JPanel pnlTab = new JPanel(f);
        pnlTab.setOpaque(false);

        // Add a JLabel with title and the left-side tab icon
        JLabel lblTitle = new JLabel(title);
        lblTitle.setIcon(icon);

        // Create a JButton for the close tab button
        JButton btnClose = new JButton();
        btnClose.setOpaque(false);

        // Configure icon and rollover icon for button
        btnClose.setIcon(new ImageIcon("D:\\def.png"));

        // Set border null so the button doesn't make the tab too big
        btnClose.setBorder(null);

        // Make sure the button can't get focus, otherwise it looks funny
        btnClose.setFocusable(false);

        // Put the panel together
        pnlTab.add(lblTitle);
        pnlTab.add(btnClose);

        // Add a thin border to keep the image below the top edge of the tab
        // when the tab is selected
        pnlTab.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

        // Now assign the component for the tab
        tabbedPane.setTabComponentAt(pos, pnlTab);

        // Add the listener that removes the tab
        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // The component parameter must be declared "final" so that it can be
                // referenced in the anonymous listener class like this.

                hmPanel.remove(c.getToolTipText());
                tabbedPane.remove(c);
            }
        };
        btnClose.addActionListener(listener);

        // Optionally bring the new tab to the front
        tabbedPane.setSelectedComponent(c);

        //-------------------------------------------------------------
        // Bonus: Adding a keystroke binding to close the tab
        //-------------------------------------------------------------
        AbstractAction closeTabAction = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                tabbedPane.remove(c);
            }
        };

        // Create a keystroke
        KeyStroke controlW = KeyStroke.getKeyStroke("control W");

        // Get the appropriate input map using the JComponent constants.
        // This one works well when the component is a container.
        InputMap inputMap = c.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        // Add the key binding for the keystroke to the action name
        inputMap.put(controlW, "closeTab");

        // Now add a single binding for the action name to the anonymous action
        c.getActionMap().put("closeTab", closeTabAction);
    }
}

No comments:

Post a Comment