How do I detect tab selection changes in JTabbedPane?

In this example you will learn how to detect tab selection changes in a JTabbedPane component. To get notified when a tab is selected you must add a ChangeListener to the JTabbedPane component using the addChangeListener(). This method take an instance of class that implements the ChangeListener interface as its arguments.

In this example we implement the ChangeListener interface in the TabbedPaneSelection class. And we need to create an implementation for the stateChanged() method as defined by this interface contract. By implementing the interface in the TabbedPaneSelection class, we don’t need to create a separate class that specifically implement this interface. That’s why in the code snippet below we just pass the current object, using the this keyword, when calling the addChangeListener() method.

The stateChanged() method of this interface will be fired every time a new tab is selected. To get the selected tab index you can use the JTabbedPane‘s getSelectedIndex() method. The index returned by the getSelectedIndex() method is zero based, it means that if you select the first tab you will get index of 0, and if you select the second tab you will get index of 1.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class TabbedPaneSelection extends JPanel implements ChangeListener {
    public TabbedPaneSelection() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TabbedPaneSelection();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTabbedPane Selection Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TabbedPaneSelection::showFrame);
    }

    private void initializeUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel dashboardPanel = new JPanel();
        tabbedPane.addTab("Dashboard", dashboardPanel);

        JPanel accountPanel = new JPanel();
        tabbedPane.addTab("Account", accountPanel);

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));
        this.add(tabbedPane, BorderLayout.CENTER);

        // Add ChangeListener to the tabbed pane.
        tabbedPane.addChangeListener(this);
    }

    public void stateChanged(ChangeEvent e) {
        JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
        int selectedIndex = tabbedPane.getSelectedIndex();
        JOptionPane.showMessageDialog(null, "Selected Index: " + selectedIndex);
    }
}

If you run the presented code snippet above you’ll get the output as shown in the image below. And if you click the tab a message dialog will be displayed showing you the selected index.

JTabbedPane Selection Demo

How do I create a simple JTabbedPane?

In this example you will learn how to use JTabbedPane to arrange some components in tabbed view. The JTabbedPane component of the Swing API allows some components such as panels to share the same view. By selecting the corresponding tab, the panel will be displayed on the user’s screen. To add tabs to the JTabbedPane class you can use the addTab() method.

To the addTab() method accept two arguments, the title of the tab and the component you wish to display as the content of the tab. In the code snippet below we will use a simple panel as the content of the tab. You can also define an image icon for the tab which makes the program looks better. You can read it in this example:

Now, let’s create a simple example of JTabbedPane which has three tabs and the corresponding content, they are the Dashboard, Transaction and Account tabs. Below is an image that show how the screen will look.

Simple JTabbedPane Demo

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class SimpleTabbedPane extends JPanel {
    public SimpleTabbedPane() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new SimpleTabbedPane();
        panel.setOpaque(true);

        JFrame frame = new JFrame("Simple Tabbed Pane Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SimpleTabbedPane::showFrame);
    }

    private void initializeUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel dashboardPanel = new JPanel();
        dashboardPanel.add(new JLabel("Dashboard"));

        // Add Dashboard Tab
        tabbedPane.addTab("Dashboard", dashboardPanel);

        JPanel transactionPanel = new JPanel();
        transactionPanel.add(new JLabel("Transaction"));

        // Add Transactions Tab
        tabbedPane.addTab("Transaction", transactionPanel);

        JPanel accountPanel = new JPanel();
        accountPanel.add(new JLabel("Account"));

        // Add Account Tab
        tabbedPane.addTab("Account", accountPanel);

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));
        this.add(tabbedPane, BorderLayout.CENTER);
    }
}

How do I overload methods in Java?

Method overloading allows a method to use the same name or identifier as the method name as long as the argument list is different. Java can differentiate each method by their method signatures. For example to print some value you can create a print method that accept different kind of objects or values as its parameters.

Overloaded method is differentiated by the number and the type of argument they accept. The print(String string) and print(int number) are distinct and unique due to their argument type.

The compiler does not count a return type as a method differentiator. So it is not legal to create a method with the same name, the same number, the same type of argument but with a different return type.

package org.kodejava.basic;

public class OverloadedExample {
    public void print(Object object) {
        System.out.println("object = " + object);
    }

    public void print(String string) {
        System.out.println("string = " + string);
    }

    public void print(int number) {
        System.out.println("number = " + number);
    }

    public void print(float number) {
        System.out.println("number = " + number);
    }

    public void print(double number) {
        System.out.println("number = " + number);
    }
}

How do I create constructors for a class?

Every class in Java has a constructor. constructor is a method that is used to create an instance or object of the class. Every time you create an instance, you must invoke a constructor.

If you do not create a constructor method of your class, the compiler will build a default one. A default constructors is a constructor that accept no argument.

Things to be noted when you declare a constructor:

  • Constructor must have the same name as the class in which they are declared.
  • Constructor can’t have a return type.
  • Constructor can have access modifier.
  • Constructor can take arguments.
  • Constructor can’t be marked static.
  • Constructor can’t be marked final or abstract.
package org.kodejava.basic;

public class ConstructorDemo {
    private String arg;
    private int x;
    private int y;

    public ConstructorDemo() {
    }

    public ConstructorDemo(String arg) {
        this.arg = arg;
    }

    public ConstructorDemo(int x) {
        this.x = x;
    }

    public ConstructorDemo(int x, int y) {
        this.y = y;
    }
}

class RunConstructor {
    public static void main(String[] args) {
        // Change the default constructor from private to public in
        // the ConstructorDemo class above then call the statement 
        // below. It will create an instance object cons0 without 
        // any error.
        ConstructorDemo cons0 = new ConstructorDemo();

        // Change the default constructor back to private, then call 
        // the statement below. ConstructorDemo() is not visible 
        // because it declared as private.
        ConstructorDemo cons1 = new ConstructorDemo();

        // invoke Constructor(String arg)
        ConstructorDemo cons2 = new ConstructorDemo("constructor");

        // invoke public Constructor(int x)
        ConstructorDemo cons3 = new ConstructorDemo(1);

        //invoke Constructor(int x, int y)
        ConstructorDemo cons4 = new ConstructorDemo(1, 2);
    }

}

How do I use the final keyword in Java?

The final modifier is used to mark a class final so that it cannot be extended, to prevent a method being overridden, and to prevent changing the value of a variable. Arguments of a method if declared as final is also can not be modified within the method.

package org.kodejava.basic;

public class FinalExample {
    // breed is declared final.
    // can't change the value assigned to breed
    public final String breed = "pig";
    private int count = 0;

    public static void main(String[] args) {
        FinalExample fe = new FinalExample();
        // assign a value to breed variable will cause a
        // compile-time error
        //
        // fe.breed = "dog";

        int number = fe.count(20);
    }

    // sound() method is declared final, so it can't be overridden
    public final void sound() {
        System.out.println("oink oink");
    }

    // number parameter is declared final. can't change the value
    // assigned to number
    public int count(final int number) {
        // assign a value to number variable will cause a
        // compile-time error
        //
        // number = 1;

        count = +number;
        return count;
    }
}

final class SubFinalExample extends FinalExample {

    // try to override sound() method of superclass will cause a
    // compile-time error
    //
    // public void sound() {
    //     System.out.println("oink");
    // }
}

// try to inherit a class that declared final will cause a
// compile-time error
//
class OtherFinalExample extends SubFinalExample {
}