gpt4 book ai didi

java - 当调用 JButton actionperformed 事件时返回一个值

转载 作者:行者123 更新时间:2023-11-30 06:26:01 24 4
gpt4 key购买 nike

我对 JButton Action 事件有一些问题,我声明了一个全局变量 (boolean tc1) 和一个 JButton t1。当我按下 JButton 时,我需要将 boolean 变量的值更改为“true”。谁能帮我吗?我的代码放在这里。

class Tracker extends JPanel {
public static void main(String[] args) {
new Tracker();
}

public Tracker() {

JButton tr=new JButton("TRACKER APPLET");
JButton rf=new JButton("REFRESH");

boolean tc1=false,tc2=false,tc3=false,tc4=false;
JButton t1=new JButton(" ");

t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tc1=true;
}
});
System.out.println(tc1);
//remaining part of the code...
// here i need to use the value of tc1 for further process..


}
}

谢谢。

最佳答案

tc1 必须是实例变量。
您可以在方法内定义的另一个类中使用局部变量,除非局部变量是 final 变量。
constructor中取出tc1的声明,使整个class

可见
  class Tracker extends JPanel {
boolean tc1=false,tc2=false,tc3=false,tc4=false;
public static void main(String[] args) {
new Tracker();
}

public Tracker() {

JButton tr=new JButton("TRACKER APPLET");
JButton rf=new JButton("REFRESH");


JButton t1=new JButton(" ");

t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tc1=true;
}
});
System.out.println(tc1);
//remaining part of the code...
// here i need to use the value of tc1 for further process..


}
}

我也遇到过这个问题,幸运的是我找到了解决方案

关于java - 当调用 JButton actionperformed 事件时返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14909401/

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