import javax.swing.JTabbedPane;

import javax.swing.ImageIcon;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JFrame;

import javax.swing.JComponent;

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.GridLayout;

import java.awt.event.KeyEvent;

public class TabbedPaneDemo extends JPanel {

public TabbedPaneDemo() {

super(new GridLayout(1, 1));

JTabbedPane tabbedPane = new JTabbedPane();

ImageIcon icon = createImageIcon("images/middle.gif");

JComponent panel1 = makeTextPanel("面板 #1");

tabbedPane.addTab("标签 1", icon, panel1,

"什么也不做");

tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);

JComponent panel2 = makeTextPanel("面板 #2");

tabbedPane.addTab("标签 2", icon, panel2,

"第二次还是什么什么也不做");

tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);

JComponent panel3 = makeTextPanel("面板 #3");

tabbedPane.addTab("标签 3", icon, panel3,

"仍然没有做什么");

tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);

JComponent panel4 = makeTextPanel(

"面板 #4 (预定义大小 410 x 50).");

panel4.setPreferredSize(new Dimension(410, 50));

tabbedPane.addTab("标签 4", icon, panel4,

"根本就没有做什么");

tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);

//吧标签加入到这个面板上

add(tabbedPane);

//取消下面注释将使用可滚动的标签

//tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

}

protected JComponent makeTextPanel(String text) {

JPanel panel = new JPanel(false);

JLabel filler = new JLabel(text);

filler.setHorizontalAlignment(JLabel.CENTER);

panel.setLayout(new GridLayout(1, 1));

panel.add(filler);

return panel;

}

/** 返回图标, 如果路径错误则返回 null. */

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("找不到文件: " + path);

return null;

}

}

/**

* 创建并显示这个 GUI，由事件分配线程来处理。

*/

private static void createAndShowGUI() {

//创建并设置窗口

JFrame frame = new JFrame("TabbedPaneDemo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//创建并设置 content 面板.

JComponent newContentPane = new TabbedPaneDemo();

newContentPane.setOpaque(true);

frame.getContentPane().add(new TabbedPaneDemo(),

BorderLayout.CENTER);

//显示这个窗口

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

//给事件分配线程一个作业：创建并显示这个 GUI

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}