2012-11-18 101 views
1

我正嘗試使用Swing創建Java程序。我試圖完成的一件事是使用MouseListener獲取JList中單擊項目的索引,並檢索與數組索引關聯的變量。我的問題是,當我嘗試調用MouseListener之外的變量時,它不會被識別。我的代碼之中:變量不能在MouseListener構造函數之外被調用

public class UserListPanel extends JPanel { 

LibraryController ctrl = new LibraryController(); 
JScrollPane scrollpane; 
public int userid; 
public String userName; 

public UserListPanel(final Borrower[] borrowersArray) { 

    String userArray [] = new String [borrowersArray.length]; 
    for (int i = 0; i < userArray.length; i++) { 
     userArray[i] = borrowersArray[i].getName(); 
    } 

    JList userList = new JList(userArray); 
    scrollpane = new JScrollPane(userList); 
    this.add(scrollpane); 

    // Adds a mouse click listener to assign values from the JList to a variable on click 
    userList.addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent evt) { 
      JList userList = (JList)evt.getSource(); 
      if (evt.getClickCount() >= 0) { 
       int index = userList.locationToIndex(evt.getPoint()); 
       ListModel dlm = userList.getModel(); 
       Object item = dlm.getElementAt(index); 
       userList.ensureIndexIsVisible(index); 
       userid = borrowersArray[index].getbID(); 
       userName = borrowersArray[index].getName(); 
       JOptionPane.showMessageDialog(null, userName); 
      } 
     } 
    }); 
} 

userid = borrowersArray[index].getbID(); 

} 

內的MouseListener構造我能得到正確的變量並將其存儲在用戶標識變量內,例如,我的JOptionPane通過返回數量證實了這一點。在構造函數之外的Hoewever中,整數「index」未被識別,因此如果我要調用userid,它將返回null。我會如何去尋找MouseListener之外的索引副本?

回答

1

如果你想indexmouseClicked方法(不是構造函數),那麼你應該初始化它的mouseClicked方法外,併爲其分配mouseClicked方法內的值,然後你就可以得到那個index構造之外。

您正在聲明和初始化indexmouseClicked方法的內部,使得變量的範圍是高達該mouseClicked方法,因此它是不提供其範圍即mouseClicked方法外的外側。

public UserListPanel(final Borrower[] borrowersArray) { 
    int index=0; 
    String userArray [] = new String [borrowersArray.length]; 
    for (int i = 0; i < userArray.length; i++) { 
     userArray[i] = borrowersArray[i].getName(); 
    } 

     ..... all other stuff 
} 
+0

你是對的,謝謝! –

+0

@JasonWu隨時歡迎! – Abubakkar

+0

實際上,沒有,經過進一步檢查,它不起作用。該變量從來沒有從MouseListener構造函數獲取值,並且默認爲0.例如,當我調用用戶名時,它總是返回與列表的第一個索引(0)關聯的名稱。顯然,構造函數外部的索引永遠不會傳入內部的整數。 –

0

index變量在MouseListener實現內聲明。因此,編譯器不理解您嘗試訪問它的任何index變量。

要解決此問題,請嘗試在偵聽器實現之外聲明index

防爆

public class UserListPanel extends JPanel { 

    LibraryController ctrl = new LibraryController(); 
    JScrollPane scrollpane; 
    public int userid; 
    public String userName; 
    public int index ; //declare it as a global (member) variable 
... 
} 
+0

顯然我忽略了這一點。感謝您的幫助! –

相關問題