/* * TabDemo.java requires no other files. It's like CardLayoutDemo, * but it uses a JTabbedPane instead of a GUI centered around * CardLayout. */ import java.awt.*; import javax.swing.*; public class TabDemo { final static String BUTTONPANEL = "JPanel with JButtons"; final static String TEXTPANEL = "JPanel with JTextField"; public void addComponentToPane(Container pane) { JTabbedPane tabbedPane = new JTabbedPane(); //Create the "cards". JPanel card1 = new JPanel() { //Make the panel wider than it really needs, so //the window's wide enough for the tabs to stay //in one row. public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width += 100; return size; } }; card1.add(new JButton("Button 1")); card1.add(new JButton("Button 2")); card1.add(new JButton("Button 3")); JPanel card2 = new JPanel(); card2.add(new JTextField("TextField", 20)); tabbedPane.addTab(BUTTONPANEL, card1); tabbedPane.addTab(TEXTPANEL, card2); pane.add(tabbedPane, BorderLayout.CENTER); } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TabDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. TabDemo demo = new TabDemo(); demo.addComponentToPane(frame.getContentPane()); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }