davidahines
davidahines

Reputation: 4094

How do I tell if the tab that I have open is the active tab in java?

I have a panel inside a jtabbed pane that I only want to refresh if the tab is visible. I tried, isShowing(), isDisplayable() and isVisible() and none of them seem to work as they check whether or not the component COULD be showing, displayable or visible.

Preferably from the context of the JPanel inside of the JTabbedPane, how do I tell if the tab the JPanel is in, is the active tab?

Upvotes: 3

Views: 4355

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You could get the JTabbedPane's model and add a ChangeListener to it. e.g.,

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

public class TabbedListener {
   private static void createAndShowUI() {
      final JTabbedPane tabbedPane = new JTabbedPane();
      for (int i = 0; i < 5; i++) {
         tabbedPane.add("Tab " + i, new JLabel("Label " + i, SwingConstants.CENTER));
      }

      tabbedPane.getModel().addChangeListener(new ChangeListener() {
         @Override
         public void stateChanged(ChangeEvent e) {
            JLabel label = (JLabel) tabbedPane.getSelectedComponent();
            System.out.println(label.getText());
         }
      });

      tabbedPane.setPreferredSize(new Dimension(500, 300));

      JFrame frame = new JFrame("TabbedListener");
      frame.getContentPane().add(tabbedPane);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

Upvotes: 5

Related Questions