Java/Swing JFC/TabbedPane
Содержание
- 1 Add a tab with a label and icon at the end of all tabs
- 2 Add a tab with a label at the end of all tabs
- 3 Add a tab with a label, icon, and tool tip at the end of all tabs
- 4 Add a tab with a label taken from the name of the component
- 5 A demonstration of the tab wrapping property of JTabbedPane
- 6 A quick test of the JTabbedPane component
- 7 Creating a JTabbedPane Container
- 8 Demonstrates the Tabbed Pane
- 9 Determining When the Selected Tab Changes in a JTabbedPane Container
- 10 Enable Scrolling Tabs in a JTabbedPane Container
- 11 Enabling and Disabling a Tab in a JTabbedPane Container
- 12 Enabling the Selection of a Tab in a JTabbedPane Container Using a Keystroke
- 13 Get the index of the first tab that matches an icon
- 14 Get the index of the tab by matching the child component
- 15 Getting and Setting the Selected Tab in a JTabbedPane Container
- 16 Getting the Tabs in a JTabbedPane Container
- 17 Insert a tab after the first tab
- 18 JTabbedPane class for displaying and manipulating
- 19 Laying Out a Screen with JTabbedPane
- 20 Moving a Tab in a JTabbedPane Container
- 21 Removing a Tab in a JTabbedPane Container
- 22 Retrieve the index of a tab when needed
- 23 Setting the Color of a Tab in a JTabbedPane Container
- 24 Setting the Location of the Tabs in a JTabbedPane Container
- 25 Setting the Size of the Divider in a JSplitPane Container
- 26 Setting the Tool Tip for a Tab in a JTabbedPane Container
- 27 TabbedPane Demo
- 28 TabbedPane Sample
- 29 TabbedPane Sample 2
- 30 TabbedPane Test
- 31 TabPane Demo
Add a tab with a label and icon at the end of all tabs
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
Icon icon = new ImageIcon("icon.gif");
pane.addTab("label", icon, component);
}
}
Add a tab with a label at the end of all tabs
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
String label = "Tab Label";
pane.addTab(label, component);
}
}
Add a tab with a label, icon, and tool tip at the end of all tabs
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
String tooltip = "Tool Tip Text";
pane.addTab("label", new ImageIcon("icon.png"), component, tooltip);
}
}
Add a tab with a label taken from the name of the component
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
component.setName("Tab Label");
pane.add(component);
}
}
A demonstration of the tab wrapping property of JTabbedPane
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// TooManyTabs.java
//A demonstration of the new tab wrapping property of JTabbedPane.
//
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
public class TooManyTabs extends JFrame {
public TooManyTabs() {
super("Too Many Tabs Test");
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contents = getContentPane();
JTabbedPane wrap = new JTabbedPane();
JTabbedPane scroll = new JTabbedPane();
scroll.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
for (int i = 1; i < 24; i++) {
String tab = "Tab #" + i;
wrap.addTab(tab, new JLabel(tab));
scroll.addTab(tab, new JLabel(tab));
}
JTabbedPane top = new JTabbedPane(JTabbedPane.RIGHT);
top.addTab("Wrap Tabs", wrap);
top.addTab("Scroll Tabs", scroll);
contents.add(top);
setVisible(true);
}
public static void main(String args[]) {
new TooManyTabs();
}
}
A quick test of the JTabbedPane component
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SimpleTab.java
//A quick test of the JTabbedPane component.
//
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
public class SimpleTab extends JFrame {
JTabbedPane jtp;
public SimpleTab() {
super("JTabbedPane");
setSize(200, 200);
Container contents = getContentPane();
jtp = new JTabbedPane();
jtp.addTab("Tab1", new JLabel("This is Tab One"));
jtp.addTab("Tab2", new JButton("This is Tab Two"));
jtp.addTab("Tab3", new JCheckBox("This is Tab Three"));
contents.add(jtp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]) {
new SimpleTab();
}
}
Creating a JTabbedPane Container
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JPanel panel = new JPanel();
int location = JTabbedPane.TOP; // or BOTTOM, LEFT, RIGHT
JTabbedPane pane = new JTabbedPane();
String label = "Tab Label";
pane.addTab(label, panel);
}
}
Demonstrates the Tabbed Pane
// : c14:TabbedPane1.java
// Demonstrates the Tabbed Pane.
// <applet code=TabbedPane1 width=350 height=200></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TabbedPane1 extends JApplet {
private String[] flavors = { "Chocolate", "Strawberry",
"Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge",
"Rum Raisin", "Praline Cream", "Mud Pie" };
private JTabbedPane tabs = new JTabbedPane();
private JTextField txt = new JTextField(20);
public void init() {
for (int i = 0; i < flavors.length; i++)
tabs.addTab(flavors[i], new JButton("Tabbed pane " + i));
tabs.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
txt.setText("Tab selected: " + tabs.getSelectedIndex());
}
});
Container cp = getContentPane();
cp.add(BorderLayout.SOUTH, txt);
cp.add(tabs);
}
public static void main(String[] args) {
run(new TabbedPane1(), 350, 200);
}
public static void run(JApplet applet, int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
} ///:~
Determining When the Selected Tab Changes in a JTabbedPane Container
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
pane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
JTabbedPane pane = (JTabbedPane) evt.getSource();
int sel = pane.getSelectedIndex();
System.out.println(sel);
}
});
}
}
Enable Scrolling Tabs in a JTabbedPane Container
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
int rows = pane.getTabRunCount();
int policy = pane.getTabLayoutPolicy(); // WRAP_TAB_LAYOUT
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
}
Enabling and Disabling a Tab in a JTabbedPane Container
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
pane.addTab("Tab Label", new JButton("Button"));
// Get index of the new tab
int index = pane.getTabCount() - 1;
// Determine whether the tab is enabled
boolean enabled = pane.isEnabledAt(index);
// Disable the tab
pane.setEnabledAt(index, false);
}
}
Enabling the Selection of a Tab in a JTabbedPane Container Using a Keystroke
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
pane.addTab("Tab Label", new JButton("button"));
int index = pane.getTabCount() - 1;
int keycode = KeyEvent.VK_L;
pane.setMnemonicAt(index, keycode);
}
}
Get the index of the first tab that matches an icon
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
ImageIcon icon = null;
int index = pane.indexOfTab(icon);
}
}
Get the index of the tab by matching the child component
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
int index = pane.indexOfComponent(component);
if (index < 0) {
// The tab could not be found
}
}
}
Getting and Setting the Selected Tab in a JTabbedPane Container
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
// Get the index of the currently selected tab
int selIndex = pane.getSelectedIndex();
// Select the last tab
selIndex = pane.getTabCount() - 1;
pane.setSelectedIndex(selIndex);
}
}
Getting the Tabs in a JTabbedPane Container
import java.awt.ruponent;
import javax.swing.Icon;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
int count = pane.getTabCount();
for (int i = 0; i < count; i++) {
String label = pane.getTitleAt(i);
Icon icon = pane.getIconAt(i);
String tooltip = pane.getToolTipTextAt(i);
boolean enabled = pane.isEnabledAt(i);
int keycode = pane.getMnemonicAt(i);
Component comp = pane.getComponentAt(i);
}
}
}
Insert a tab after the first tab
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
int index = 1;
pane.insertTab("label", new ImageIcon("icon.png"), component, "tooltip", index);
}
}
JTabbedPane class for displaying and manipulating
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SysConfig.java
//A demonstration of the JTabbedPane class for displaying and manipulating
//configuration information. The BoxLayout class is used to layout the
//first tab quickly.
//
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
public class SysConfig extends JFrame {
JTabbedPane config = new JTabbedPane();
public SysConfig() {
super("JTabbedPane & BoxLayout Demonstration");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel configPane = new JPanel();
configPane.setLayout(new BoxLayout(configPane, BoxLayout.Y_AXIS));
JTextArea question = new JTextArea("Which of the following options\n"
+ "do you have installed?");
// Ok, now configure the textarea to show up properly inside the box.
// This is part of the "high art" of Swing...
question.setEditable(false);
question.setMaximumSize(new Dimension(300, 50));
question.setAlignmentX(0.0f);
question.setBackground(configPane.getBackground());
JCheckBox audioCB = new JCheckBox("Sound Card", true);
JCheckBox nicCB = new JCheckBox("Ethernet Card", true);
JCheckBox tvCB = new JCheckBox("Video Out", false);
configPane.add(Box.createVerticalGlue());
configPane.add(question);
configPane.add(audioCB);
configPane.add(nicCB);
configPane.add(tvCB);
configPane.add(Box.createVerticalGlue());
JLabel audioPane = new JLabel("Audio stuff");
JLabel nicPane = new JLabel("Networking stuff");
JLabel tvPane = new JLabel("Video stuff");
JLabel helpPane = new JLabel("Help information");
audioCB.addItemListener(new TabManager(audioPane));
nicCB.addItemListener(new TabManager(nicPane));
tvCB.addItemListener(new TabManager(tvPane));
config.addTab("System", null, configPane, "Choose Installed Options");
config.addTab("Audio", null, audioPane, "Audio system configuration");
config.addTab("Networking", null, nicPane, "Networking configuration");
config.addTab("Video", null, tvPane, "Video system configuration");
config.addTab("Help", null, helpPane, "How Do I...");
getContentPane().add(config, BorderLayout.CENTER);
}
class TabManager implements ItemListener {
Component tab;
public TabManager(Component tabToManage) {
tab = tabToManage;
}
public void itemStateChanged(ItemEvent ie) {
int index = config.indexOfComponent(tab);
if (index != -1) {
config.setEnabledAt(index,
ie.getStateChange() == ItemEvent.SELECTED);
}
SysConfig.this.repaint();
}
}
public static void main(String args[]) {
SysConfig sc = new SysConfig();
sc.setVisible(true);
}
}
Laying Out a Screen with JTabbedPane
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class TabbedPaneTest {
public static void main(String args[]) {
JFrame frame = new JFrame("JTabbedPane");
final Container contentPane = frame.getContentPane();
JTabbedPane jtp = new JTabbedPane();
contentPane.add(jtp, BorderLayout.CENTER);
for (int i = 0; i < 5; i++) {
JButton button = new JButton("Card " + i);
jtp.add("Btn " + i, button);
}
frame.setSize(300, 200);
frame.show();
}
}
Moving a Tab in a JTabbedPane Container
import java.awt.Color;
import java.awt.ruponent;
import javax.swing.Icon;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
int src = pane.getTabCount() - 1;
int dst = 0;
Component comp = pane.getComponentAt(src);
String label = pane.getTitleAt(src);
Icon icon = pane.getIconAt(src);
Icon iconDis = pane.getDisabledIconAt(src);
String tooltip = pane.getToolTipTextAt(src);
boolean enabled = pane.isEnabledAt(src);
int keycode = pane.getMnemonicAt(src);
int mnemonicLoc = pane.getDisplayedMnemonicIndexAt(src);
Color fg = pane.getForegroundAt(src);
Color bg = pane.getBackgroundAt(src);
pane.remove(src);
pane.insertTab(label, icon, comp, tooltip, dst);
pane.setDisabledIconAt(dst, iconDis);
pane.setEnabledAt(dst, enabled);
pane.setMnemonicAt(dst, keycode);
pane.setDisplayedMnemonicIndexAt(dst, mnemonicLoc);
pane.setForegroundAt(dst, fg);
pane.setBackgroundAt(dst, bg);
}
}
Removing a Tab in a JTabbedPane Container
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
JButton component = new JButton("button");
// Remove the last tab
pane.remove(pane.getTabCount() - 1);
// Remove the tab with the specified child component
pane.remove(component);
// Remove all the tabs
pane.removeAll();
}
}
Retrieve the index of a tab when needed
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
// Get the index of the first tab that matches a label
String label = "Tab Label";
int index = pane.indexOfTab(label);
}
}
Setting the Color of a Tab in a JTabbedPane Container
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
pane.setForeground(Color.YELLOW);
pane.setBackground(Color.MAGENTA);
String label = "Tab Label";
pane.addTab(label, new JButton("Button"));
int index = pane.getTabCount() - 1;
pane.setForegroundAt(index, Color.ORANGE);
pane.setBackgroundAt(index, Color.GREEN);
}
}
Setting the Location of the Tabs in a JTabbedPane Container
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
int loc = pane.getTabPlacement();
int location = JTabbedPane.LEFT; // or TOP, BOTTOM, RIGHT
pane = new JTabbedPane(location);
pane.setTabPlacement(JTabbedPane.BOTTOM);
}
}
Setting the Size of the Divider in a JSplitPane Container
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton leftComponent = new JButton("left");
JButton rightComponent= new JButton("right");
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
int size = pane.getDividerSize();
size = 1;
pane.setDividerSize(size);
}
}
Setting the Tool Tip for a Tab in a JTabbedPane Container
import javax.swing.JButton;
import javax.swing.JTabbedPane;
public class Main {
public static void main(String[] argv) throws Exception {
JTabbedPane pane = new JTabbedPane();
String label = "Tab Label";
String tooltip = "Tool Tip Text";
pane.addTab(label, null, new JButton("Button"), tooltip);
int index = pane.getTabCount() - 1;
tooltip = pane.getToolTipTextAt(index);
tooltip = "New Tool Tip Text";
pane.setToolTipTextAt(index, tooltip);
}
}
TabbedPane Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* TabbedPaneDemo.java is a 1.4 example that requires one additional file:
* images/middle.gif.
*/
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("Panel #1");
tabbedPane.addTab("Tab 1", icon, panel1, "Does nothing");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JComponent panel2 = makeTextPanel("Panel #2");
tabbedPane.addTab("Tab 2", icon, panel2, "Does twice as much nothing");
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
JComponent panel3 = makeTextPanel("Panel #3");
tabbedPane.addTab("Tab 3", icon, panel3, "Still does nothing");
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
JComponent panel4 = makeTextPanel("Panel #4 (has a preferred size of 410 x 50).");
panel4.setPreferredSize(new Dimension(410, 50));
tabbedPane.addTab("Tab 4", icon, panel4, "Does nothing at all");
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
//Add the tabbed pane to this panel.
add(tabbedPane);
//Uncomment the following line to use scrolling tabs.
//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;
}
/** Returns an ImageIcon, or null if the path was invalid. */
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("Couldn"t find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TabbedPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new TabbedPaneDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.getContentPane().add(new TabbedPaneDemo(), BorderLayout.CENTER);
//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();
}
});
}
}
TabbedPane Sample
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class TabSample {
static void addIt(JTabbedPane tabbedPane, String text) {
JLabel label = new JLabel(text);
JButton button = new JButton(text);
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
tabbedPane.addTab(text, panel);
}
public static void main(String args[]) {
JFrame f = new JFrame("JTabbedPane Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JTabbedPane tabbedPane = new JTabbedPane();
addIt(tabbedPane, "Tab One");
addIt(tabbedPane, "Tab Two");
addIt(tabbedPane, "Tab Three");
addIt(tabbedPane, "Tab Four");
addIt(tabbedPane, "Tab Five");
content.add(tabbedPane, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
TabbedPane Sample 2
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TabbedPaneSample {
static Color colors[] = { Color.red, Color.orange, Color.yellow,
Color.green, Color.blue, Color.magenta };
static void add(JTabbedPane tabbedPane, String label) {
int count = tabbedPane.getTabCount();
JButton button = new JButton(label);
button.setBackground(colors[count]);
tabbedPane.addTab(label, new DiamondIcon(colors[count]), button, label);
}
public static void main(String args[]) {
String title = (args.length == 0 ? "Tabbed Pane Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
String titles[] = { "General", "Security", "Content", "Connection",
"Programs", "Advanced" };
for (int i = 0, n = titles.length; i < n; i++) {
add(tabbedPane, titles[i]);
}
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent
.getSource();
int index = sourceTabbedPane.getSelectedIndex();
System.out.println("Tab changed to: "
+ sourceTabbedPane.getTitleAt(index));
}
};
tabbedPane.addChangeListener(changeListener);
Container contentPane = frame.getContentPane();
contentPane.add(tabbedPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
class DiamondIcon implements Icon {
private Color color;
private boolean selected;
private int width;
private int height;
private Polygon poly;
private static final int DEFAULT_WIDTH = 10;
private static final int DEFAULT_HEIGHT = 10;
public DiamondIcon(Color color) {
this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected) {
this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected, int width, int height) {
this.color = color;
this.selected = selected;
this.width = width;
this.height = height;
initPolygon();
}
private void initPolygon() {
poly = new Polygon();
int halfWidth = width / 2;
int halfHeight = height / 2;
poly.addPoint(0, halfHeight);
poly.addPoint(halfWidth, 0);
poly.addPoint(width, halfHeight);
poly.addPoint(halfWidth, height);
}
public int getIconHeight() {
return height;
}
public int getIconWidth() {
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.translate(x, y);
if (selected) {
g.fillPolygon(poly);
} else {
g.drawPolygon(poly);
}
g.translate(-x, -y);
}
}
TabbedPane Test
/**
* @version 1.00 1999-07-17
* @author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class SwingTabbedPaneTest {
public static void main(String[] args)
{ JFrame frame = new TabbedPaneFrame();
frame.show();
}
}
class TabbedPaneFrame extends JFrame
implements ChangeListener
{ public TabbedPaneFrame()
{ setTitle("TabbedPaneTest");
setSize(400, 300);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
tabbedPane = new JTabbedPane();
tabbedPane.addChangeListener(this);
/* we set the components to null and delay their
loading until the tab is shown for the first time
*/
ImageIcon icon = new ImageIcon("yellow-ball.gif");
tabbedPane.addTab("Mercury", icon, null);
tabbedPane.addTab("Venus", icon, null);
tabbedPane.addTab("Earth", icon, null);
tabbedPane.addTab("Mars", icon, null);
tabbedPane.addTab("Jupiter", icon, null);
tabbedPane.addTab("Saturn", icon, null);
tabbedPane.addTab("Uranus", icon, null);
tabbedPane.addTab("Neptune", icon, null);
tabbedPane.addTab("Pluto", icon, null);
getContentPane().add(tabbedPane, "Center");
}
public void stateChanged(ChangeEvent event)
{ JTabbedPane pane = (JTabbedPane)event.getSource();
// check if this tab still has a null component
if (pane.getSelectedComponent() == null)
{ // set the component to the image icon
int n = pane.getSelectedIndex();
String title = pane.getTitleAt(n);
ImageIcon planetIcon = new ImageIcon(title + ".gif");
pane.setComponentAt(n, new JLabel(planetIcon));
// indicate that this tab has been visited--just for fun
pane.setIconAt(n, new ImageIcon("red-ball.gif"));
}
}
private JTabbedPane tabbedPane;
}
TabPane Demo
import javax.swing.*;
public class TabPaneDemo {
protected JTabbedPane tabPane;
public TabPaneDemo() {
tabPane = new JTabbedPane();
tabPane.add(new JLabel("One", JLabel.CENTER), "First");
tabPane.add(new JLabel("Two", JLabel.CENTER), "Second");
}
public static void main(String[] a) {
JFrame f = new JFrame("Tab Demo");
f.getContentPane().add(new TabPaneDemo().tabPane);
f.setSize(120, 100);
f.setVisible(true);
}
}