Question

I'm having some difficulties in retrieving values from one java class into another. I have this Login.java, it has a userIDField which is a textfield that allows the user to enter his/her userID. I added a getter in this Login.java.

public String getUserID(){
   return userIDField.getText();
}

then I have a AddSale.java that calls the getUserID method to get the userID entered by the user. I'm accessing this via the confirmAddSales button.

private Login log = new Login();

private void confirmAddSalesActionPerformed(java.awt.event.ActionEvent evt) {                                                
    String sample = log.getUserID();
    System.out.println(sample+"<------------------check if sample is working");
}

but there is no result for the String "sample" in the AddSale.java, please help in resolving this. thank you.

Was it helpful?

Solution

Sorry, I didn't see your request for an example. If the GUI is in class Main which is also where your main method is, and it creates both the text field and the AddSale object, you could do something like this:

public class Main() {
    JTextField userIDField;

    public static void main(String[] args) {
        userIDField = new JTextField();
        Login login = new Login(userIDField);
        AddSale addSale = new AddSale(userIDField);
        Frame frame = new JFrame();
        // ... and so on ...
        button.addActionListener(addSale);
    }
}

public class AddSale implements ActionListener {
    private final Login login;

    public AddSale(Login login) {
        this.login = login;
    }

    private void confirmAddSalesActionPerformed(java.awt.event.ActionEvent evt) {                                                
        String sample = login.getUserID();
        System.out.println(sample+"<------------------check if sample is working");
    }
}

This way, the Login object, the AddSale object, and any other parts of your program are all referring to the same Login object and text field. This may not quite be the right relationship since you haven't told us anything about how your classes get created, or what they're called, but this is the general approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top