Where The Streets Have No Name

Dynamic JTabbedPane 본문

Developement/Java

Dynamic JTabbedPane

highheat 2010. 2. 10. 16:40
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class TabbedTest extends JFrame {

    private JTabbedPane jtp = new JTabbedPane();
    static int count = 0;

    public TabbedTest() {
        JButton add = new JButton("Add Tab");
        add.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                addNewTab("" + (++count));
            }
        });
        JButton remove = new JButton("Remove Tab");
        remove.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                removeTab();
                count--;
            }
        });
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(add);
        buttonPanel.add(remove);
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.setPreferredSize(new Dimension(200, 200));
        content.add(buttonPanel, BorderLayout.NORTH);
        content.add(jtp, BorderLayout.CENTER);
        this.setContentPane(content);
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    protected void removeTab() {
        Component c = jtp.getSelectedComponent();
        jtp.remove(c);
    }

    protected void addNewTab(String name) {
        JLabel jl = new JLabel(name);
        JPanel jp = new JPanel();
        jp.add(jl);
        jtp.add(name, jp);
        jtp.setSelectedComponent(jp);
    }

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