Access the internal elements of a jFrame from another class

1

What I want to know is how I can access elements like jTextField or jLabel of a jFrame without putting them public static from within the netbeans settings

    
asked by David Calderon 10.06.2016 в 01:29
source

2 answers

1

It simply provides the properties getters and setters to access them.

private JTextField txtNombre;

public JTextField getTxtNombre() { return txtNombre; }

public void setTxtNombre(JTextField txtNombre) {
    this.txtNombre = txtNombre;
}

Additionally, I recommend dividing your application into layers. You can have the logic in one layer, in another the forms and in another the classes that handle the forms (controllers), using the MVC pattern.

For example:

Form

public class FormRegistro extends JFrame {

    private JButton btnRegistrar;
    private FormRegistroController controller;

    public FormRegistro() {
        super("Registro de personal");
        controller = new FormRegistroController(this);
        initComponents();
    }

    private void initComponents() {
        ...
        btnRegistrar = new JButton("Registrar");
        btnRegistrar.addActionListener(controller);
    }
}

This form will be handled by a controller. This will be responsible for listening to the events that occur in the form and will act according to them.

Driver

public class FormRegistroController implements ActionListener {

    private FormRegistro ui;

    public FormRegistroController(FormRegistro ui) {
        this.ui = ui;
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String actionCommand = event.getActionCommand();
        if(actionCommand.equals("Registrar")) {
           // se ha clickeado el botón registrar
           String nombre = ui.getTextNombre().getText();
           // obtienes los demás valores y luego registras
        }
    }
}

It is good that from the beginning you worry about following good standards and programming practices, they will greatly reinforce your learning. Later, when you see database you can use the DAO or Repository pattern for example.

    
answered by 10.06.2016 / 01:46
source
0

I do not have your code so what I have is an idea of what you are doing, my opinion is as follows.

Create a public method within your Jframe that returns the controls of the Jframe within these frame controls are your JtextField and all the other controls. If you use this idea you should keep in mind that you have to mark the controls that you want to return in some way, as it may happen that you accidentally take unwanted controls.

    
answered by 10.06.2016 в 01:50