我試圖從 actionPerformed 類中獲取 int 變數中的值,整數來自另一個類,其中它作為引數“asd”傳遞并保存值“1”。我顯然從下面發布的代碼中洗掉了一些行,以使其更易于閱讀,但我洗掉的內容與我遇到的問題無關。所以在這里,我看到的輸出是;
asd
1
1
0
0
最后兩個輸出來自 actionPerformed 類,當我單擊相關按鈕時它們會出現。我怎樣才能使這 2 個輸出也顯示為 1?
public class customerAppointmentScreen extends JFrame implements ActionListener{
private JButton massB,indiB;
public int asd,id;
public customerAppointmentScreen(int asd) {
System.out.println("asd ");
System.out.println(asd);
id=asd;
System.out.println(id);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==massB) {
int id=asd;
System.out.println(asd);
System.out.println(id);
//this.setVisible(false);
}
else if(e.getSource()==indiB) {
this.setVisible(false);
}
}
}
uj5u.com熱心網友回復:
從...開始...
public int asd,id;
public customerAppointmentScreen(int asd) {
System.out.println("asd ");
System.out.println(asd);
id=asd;
System.out.println(id);
}
引數asd永遠不會分配給實體欄位asd,因此實體欄位仍然存在0(id另一方面等于引數asd)
當ActionListener觸發...
public void actionPerformed(ActionEvent e) {
if (e.getSource() == massB) {
int id = asd;
System.out.println(asd);
System.out.println(id);
//this.setVisible(false);
} else if (e.getSource() == indiB) {
this.setVisible(false);
}
}
您將實體欄位asd值分配給區域變數id,因為asd仍然為零,所以id.
“簡單”的解決方案是將建構式中的引數分配給適當的實體欄位ActionListener,或者根據您的意圖使用正確的實體欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473752.html
