gpt4 book ai didi

java - 如何访问 JButton ActionListener 中的变量?

转载 作者:行者123 更新时间:2023-12-01 18:15:28 26 4
gpt4 key购买 nike

希望这不会太困惑,我是java新手。我不知道如何访问 ActionListener 之外的“iDaysAlive”变量。

    JButton jButton_Calculate = new JButton("Calculate");
jButton_Calculate.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent arg0) {

int iDayBirth = Integer.parseInt(jTextField_DoBDay.getText());
int iMonthBirth = Integer.parseInt(jTextField_DoBMonth.getText());
int iYearBirth = Integer.parseInt(jTextField_DoBYear.getText());

int iDayCurrent = Integer.parseInt(jTextField_CdDay.getText());
int iMonthCurrent = Integer.parseInt(jTextField_CdMonth.getText());
int iYearCurrent = Integer.parseInt(jTextField_CdYear.getText());

double iDaysAlive;

Calendar caBirthDate = new GregorianCalendar(iYearBirth, iMonthBirth - 1, iDayBirth);
Calendar caCurrentDate = new GregorianCalendar(iYearCurrent, iMonthCurrent - 1, iDayCurrent);

iDaysAlive = caCurrentDate.getTimeInMillis() - caBirthDate.getTimeInMillis();
iDaysAlive = iDaysAlive / (24 * 60 * 60 * 1000) + 1; //this variable
}
});

jButton_Calculate.setFont(new Font("Calibri", Font.BOLD, 15));
jButton_Calculate.setBounds(180, 205, 103, 23);
frame.getContentPane().add(jButton_Calculate);

JLabel lblDaysAlive = new JLabel("Days Alive: " + iDaysAlive);

//iDaysAlive cannot be resolved to a variable

lblDaysAlive.setFont(new Font("Calibri", Font.BOLD, 18));
lblDaysAlive.setBounds(135, 257, 147, 21);
frame.getContentPane().add(lblDaysAlive);

最佳答案

要访问匿名类外部的变量,必须在外部声明它,并且它必须是 final

在你的情况下,这是行不通的,因为如果你进入双 final ,你就无法改变它。因此,您可以使用具体类而不是匿名类将结果存储在属性中以便稍后访问它。或者,您可以使用结果的辅助类,该类可以声明为最终结果,并包含要从匿名操作监听器更改的属性。或者您可以将其简单地设置为封闭类的属性。

关于java - 如何访问 JButton ActionListener 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com