File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JTabbedPane Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTabbedPane" Watch "JTabbedPane" New topic


Patrick Mugabe
Ranch Hand

Joined: Jan 08, 2002
Posts: 132
I am using JTabbedPane.I want to use call a JFrame when I click tab2. I am not sure how the event handling works with Tabs.

This is my code: It's just a Test, you can do it in a different way just to explain:

import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;

public class TabPanel extends JPanel {
Component panel1,panel2, panel3;;

public TabPanel() {
//JPanel panel = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();

JTabbedPane jTabbedPane1 = new javax.swing.JTabbedPane();
JTabbedPane jTabbedPane2 = new javax.swing.JTabbedPane();

panel1 = makeTextPanel("This is a Test: panel1");
tabbedPane.addTab("Tab One",panel1);

panel2 = makeTextPanel("This is a Test: panel2");
tabbedPane.addTab("Tab Two",panel2);
tabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {

//Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));

private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
Object obj = evt.getSource();
//if tab2 is selected,I want to call another frame
JFrame frame2 = new JFrame();

protected Component makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
panel.setLayout(new GridLayout(1, 1));
return panel;

public static void main(String[] args) {
JFrame frame = new JFrame("TabPanel");

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)

System.out.println("This is a Test :: inside main");

frame.getContentPane().add(new TabPanel(),
frame.setSize(400, 125);


Patrick Mugabe
Ranch Hand

Joined: Jan 08, 2002
Posts: 132
I think I am making progress.

There is a getSelectedIndex() method for Tabs. So if I select the first tab, it's 0, second tab it's 1 e.t.c. So I think once I have the selectedIndex value, I can call the frame I want.
Brian Mozhdehi
Ranch Hand

Joined: Aug 17, 2006
Posts: 81
you can alter your class to implement ChangeListener. Then, implement the method stateChanged(ChangeEvent e). In here, do getSelectedIndex() on your JTabbedPane (which would return 1 for tab 2) and call your frame.

When the user clicks any of the tabs, that method will automatically be called.
It is sorta covered in the JavaRanch Style Guide.
subject: JTabbedPane