Monday, March 4, 2013

Dynamically Adding Panel to 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 javax.swing.*;

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

    private JTabbedPane tabbedPane;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton createTabButton;
    private static final Icon CLOSE_TAB_ICON = new ImageIcon("Image Location");
    private int tabCount = 0;

    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();
            }
        });
    }

    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.addContainer(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 addContainer(Container container) {
        tabbedPane = new javax.swing.JTabbedPane();
        buttonPanel = new javax.swing.JPanel();

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

        createTabButton = new javax.swing.JButton();

        createTabButton.setText("Add New Tab");
        createTabButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createTabButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(createTabButton);

        container.add(buttonPanel, java.awt.BorderLayout.SOUTH);


    }

    private void createTabButtonActionPerformed(java.awt.event.ActionEvent evt) {
        tabCount++;
        JScrollPane scrollPane = new JScrollPane(new JTextArea("New tab number " + tabCount));
        addClosableTab(tabbedPane, scrollPane, "Tab " + tabCount);
    }

    /**
     * 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 JComponent
     * @param title the title for the tab
     */
    public static void addClosableTab(final JTabbedPane tabbedPane, final JComponent c, final String title
            ) {
        // 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);

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

        // Configure icon and rollover icon for button
        btnClose.setIcon(CLOSE_TAB_ICON);

        // 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.
                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