ChangeListener未按预期用于JTabbedPane

时间:2017-05-30 21:06:09

标签: java swing changelistener

我想检测选项卡何时更改并检索所选索引。我能找到的所有例子都显得已经过时,我无法成功实施它们。

它迫使我将我的changeListener强制转换为javax.swing.event.ChangeListener,但同时我不能编译它。我哪里错了?

ChangeListener changeListener = new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
            int index = sourceTabbedPane.getSelectedIndex();
            System.out.println("Tab changed to: " + index);
          }

        @Override
        public void changed(ObservableValue arg0, Object arg1, Object arg2) {
            // TODO Auto-generated method stub

        }
        };
        tabbedPane.addChangeListener((javax.swing.event.ChangeListener) changeListener);

2 个答案:

答案 0 :(得分:5)

当您调用ChangeListener时,您正在实施错误的new ChangeListener。检查你的进口。您应该实施javax.swing.event.ChangeListener,但看起来您实际上正在实施javafx.beans.value.ChangeListener

如果您不想更改导入,以下内容也可以。

  javax.swing.event.ChangeListener changeListener = new javax.swing.event.ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
        int index = sourceTabbedPane.getSelectedIndex();
        System.out.println("Tab changed to: " + index);
      }
    };
    tabbedPane.addChangeListener(changeListener);

答案 1 :(得分:2)

正在导入错误的ChangeListener - 检查相应的import语句。它应该是

import javax.swing.event.ChangeListener;
// or import javax.swing.event.*;

可能正在输入错误的类,如:

import javafx.beans.value.ChangeListener;
// or import javafx.beans.value.*;

如果需要这些导入(javaFX),则在创建侦听器时必须使用完全限定的类名:

javax.swing.event.ChangeListener changeListener = 
    new javax.swing.event.ChangeListener() {
        ...