开发者

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

开发者 https://www.devze.com 2023-03-23 23:38 出处:网络
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

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.

Pre开发者_如何学Pythonferably 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?


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();
         }
      });
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消