我在jtabbed窗格中有一个面板,如果选项卡可见,我只想刷新。我试过,isShowing(),isDisplayable()和isVisible(),它们似乎都不起作用,因为它们检查组件是否可以显示,可显示或可见。
最好从JTabbedPane内部的JPanel的上下文中,如何判断JPanel所在的选项卡是否为活动选项卡?
答案 0 :(得分:4)
您可以获取JTabbedPane的模型并向其添加ChangeListener。如,
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();
}
});
}
}