-1
I have a JPanel
which contains all graphic elements, input text fields etc. This is a different class, which needs to know all the attributes of the Jpanel. The problem is that you are not accessing the class member JPanel
, I have tried to declare the components as public private and default
public class TrataEventosClass implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null,"YOU JUST CLICKED A BUTTON!");
JOptionPane.showMessageDialog(null,txt1.getText()); // txt1 nao aparece mesmo sendo public na outra classe.
}
}
Panel class
public class JPanelClass extends JPanel {
JTextField txt1;
JTextField txt2;
JButton btn1;
JButton btn2;
JPanelClass(){
this.setLayout(new GridLayout());
iniciarElementos();
//
}
private void iniciarElementos(){
txt1 = new JTextField(10);
add(txt1);
txt2 = new JTextField(10);
add(txt2);
btn1 = new JButton("Salvar");
btn1.addActionListener(new TrataEventosClass());
add(btn1);
btn2 = new JButton("Limpar campos");
add(btn2);
}
}
This listerner is being applied to the Jtextfield that you’re trying to get the text?
– user28595
No, it is being applied to a button. q will take the text from every form and save it to a txt.
– Igor Augusto
Is there a need for a separate class for Istener really? If it will apply only to one button, I see no need to create a new class to handle the event.
– user28595
The problem is I’m trying to do it in another class. if I give an addActionListener(new Actionlistener(){});, in the same right class, I can access the components and their methods. but now I’m trying to make the eventhandler another class. but I can’t access the methods of the components...
– Igor Augusto
If you want to create a class the part of Ner to access a component that is not even linked is not a good practice in swing. What is certain is only the screen class have access to its components, violate this only when there is no other way for some project requirement, although I have never seen this need. You can create a getter in the panel class for jtexfield, which is to reinvent the wheel in my opinion.
– user28595
perfect, it is easier to create the Actionlistener in the same class. I thought it was not cool to do this, but anyway. thank you very much!
– Igor Augusto
If you want to have class on its own, instead of using class anonymity, you make an Index class. This way you keep the same current structure, but the system will have access to the components, because it will also be part of the screen class.
– user28595