How to access member of another class? [closed]

-1

I have a JPanel that contains all graphic elements, text fields buttons etc. This is a different class, which needs to know all the attributes of JPanel. The problem is that you are not accessing the member of class JPanel , already 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);

    }
}
    
asked by anonymous 04.03.2017 / 02:54

1 answer

0

You can achieve this access by transforming your TrataEventosClass class as an inner class of JPanelClass :

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);

    }

    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.
        }

    }

}
    
04.03.2017 / 03:17