gpt4 book ai didi

java - 静态变量看不到

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

我的代码中的不同面板有不同的文件,并且我想为操作监听器添加一个文件。我已将变量声明为静态,以便操作监听器可以看到它们,但看不到它们。

import java.awt.*;
import javax.swing.*;

class Respuestas extends JPanel{

static JRadioButton cb1 =new JRadioButton("1");
static JRadioButton cb2 =new JRadioButton("2");
static JRadioButton cb3 =new JRadioButton("3");
static JRadioButton cb4 =new JRadioButton("4");
static JRadioButton cb5 =new JRadioButton("5");

public Respuestas(){

setLayout(new GridLayout(1,5));

this.add(cb1);
this.add(cb2);
this.add(cb3);
this.add(cb4);
this.add(cb5);

Manejador manejador = new Manejador();
cb1.addActionListener(manejador);
cb2.addActionListener(manejador);
cb3.addActionListener(manejador);
cb4.addActionListener(manejador);
cb5.addActionListener(manejador);
}
}
import javax.swing.*;

class Botones extends JPanel{

public static JButton sig = new JButton("Siguiente");

public Botones(){

this.add(sig);

Manejador manejador = new Manejador();
sig.addActionListener(manejador);

}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Manejador implements ActionListener{

public void actionPerformed (ActionEvent evento) {

if(evento.getSource()==sig) { //Error
System.out.println("Siguiente");
}
else if(evento.getSource()==cb1) { //Error
System.out.println("1");
}
else if(evento.getSource()==cb2) { //Error
System.out.println("2");
}
else if(evento.getSource()==cb3) { //Error
System.out.println("3");
}
else if(evento.getSource()==cb4) { //Error
System.out.println("4");
}
else if(evento.getSource()==cb5) { //Error
System.out.println("5");
}

}
}

最佳答案

首先,您必须将变量声明为公共(public):

public static JRadioButton cb3 =new JRadioButton("3");

要读取该值,您必须从类中调用它,如下所示:

Respuestas.cb1;

你的actionPerformed方法应该是这样的:

public void actionPerformed (ActionEvent evento) {

if(evento.getSource()==Botones.sig) { //Error
System.out.println("Siguiente");
}
else if(evento.getSource()==Respuestas.cb1) { //Error
System.out.println("1");
}
else if(evento.getSource()==Respuestas.cb2) { //Error
System.out.println("2");
}
else if(evento.getSource()==Respuestas.cb3) { //Error
System.out.println("3");
}
else if(evento.getSource()==Respuestas.cb4) { //Error
System.out.println("4");
}
else if(evento.getSource()==Respuestas.cb5) { //Error
System.out.println("5");
}

}

关于java - 静态变量看不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399743/

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