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.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024