I have different files for different panels in my code, and I want to add a file for the action listener. I have declared my variables as static so the action listener can see them but it doesn't see them.
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");
}
}
}
First of all you have to declare your variables as public:
public static JRadioButton cb3 =new JRadioButton("3");
and to read that value you have to call it from the class like this:
Respuestas.cb1;
your actionPerformed method should be like this:
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");
}
}