我需要检测所选标签何时发生变化,并获取其索引。
以下代码有效,但它触发 println
的次数与当前加载的选项卡数量一样多:
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("Tab: " + tabbedPane.getSelectedIndex());
// Prints the string 3 times if there are 3 tabs etc
}
});
这样做的正确方法是什么?
最佳答案
通过 JDK 6 Update 26(Windows 7 64 位),我只收到以下演示代码的一个事件:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setBounds(0, 0, 300, 400);
frame.setLayout(null);
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("One", new JPanel());
tabbedPane.addTab("Two", new JPanel());
tabbedPane.addTab("Three", new JPanel());
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("Tab: " + tabbedPane.getSelectedIndex());
}
});
tabbedPane.setBounds(0, 0, 300, 400);
frame.add(tabbedPane);
frame.setVisible(true);
}
你能在调试器中弄清楚为什么监听器会被触发 3 次吗?
关于java - JTabbedPane ChangeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799731/