[英]Transferring Integers from one class to another
我有以下問題:
在我的主班里,我有以下幾行:
Integer i;
update.addActionListener(new RewardUpdater(this));
if (argument) {
i++;
}
在RewardUpdater類中,我有這個:
int i;
this.i = frame.i;
rewardButtonAddition.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateCenterPanel.removeAll();
c.repaint();
text.setText("Test: " + i);
c.add(beschriftung);
updateCenterPanel.add(additionReward1);
updateCenterPanel.add(additionReward2);
updateCenterPanel.add(additionReward3);
}
});
但是無論我多久為i ++完成一次if迭代;
我的我總是打印為0。
抱歉,代碼有限,整個過程都很混亂,我只想把必要的東西放在這里。 如果需要更多,我可以提供。
感謝您的簡短答復!
真誠的莫里茨
在actionPerformed
方法中,應從框架中獲取i的值。 否則,在構造偵聽器時,僅從框架獲取一次該值,並且永遠不會更改。
因此,簡而言之,更換
text.setText("Test: " + i);
通過
text.setText("Test: " + frame.i);
並從RewardUpdater
刪除無用的i
字段。
如果您想讓您的Action
(例如JButton
click)增加該值,則可以在ActionListener
添加i++
。
另一方面,如果您想在其他地方增加該值,我建議創建一個新類,如下所示:
public class RewardValue {
private int value;
public RewardValue(int startValue) {
this.value = startValue;
}
public void increment() {
value++;
}
public int getValue() {
return value;
}
}
然后,您可以繼續創建RewardValue
並將其傳遞到需要的地方。 您基本上將i
與RewardValue
交換。 應該在有i++
的地方調用公共方法increment
。 公共方法get
在那里,因此您可以讀取新i
的值。 一個小例子如下:
public class MainClass {
private final RewardValue rewardValue = new RewardValue(0);
public MainClass() {
//initiate update
//...
update.addActionListener(new RewardUpdater(rewardValue));
//of cause the next lines don't need to be in the constructor
if (argument) {
rewardUpdater.increment();
}
}
}
public class RewardUpdater implements ActionListener {
private final RewardValue rewardValue;
public RewardUpdater(RewardValue rewardValue) {
this.rewardValue = rewardValue;
}
public void actionPerformed(AcionEvent e) {
//... the other lines
text.setText("Test: "+rewardValue.get());
// ... the other lines
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.