2017-05-30 84 views
0

我想檢測選項卡何時發生變化並檢索選定的索引。我所能找到的所有例子都顯得過時,並且我無法成功實現它們。ChangeListener不按預期方式工作JTabbedPane

它強制我將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); 

回答

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); 
2

正在導入錯誤的ChangeListener - 檢查相應的導入語句。它應該是

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() { 
     ...