Search code examples
javaencapsulationgetter-setter

Passing data to other classes via getter/setter


I'm having issues passing data from a GUI to other classes. Everything is initialized in the GUI and then from there the data is passed to another class where additional changes may take place: (simplified and missing parts for compilation)

class GUI extends JFrame {
final Configuration conf = new Configuration();

GUI() {
    initComponents();
}

private void initComponents() {

    //Setup default values
    conf.expectFires(false);
    conf.expectRain(false);
    conf.expectDisaster(true);

    JComboBox<String> seasonTypes = new JComboBox<>(new String[]{"Winter", "Spring", "Summer", "Fall"});

    seasonTypes.setSelectedIndex(0);
    conf.setSeason(seasonTypes.getItemAt(seasonTypes.getSelectedIndex()));

    //Action listener for dynamic changes to whatever is selected
    seasonTypes.addActionListener(e -> {
        String season = seasonTypes.getSelectedItem().toString();
        if (!season.equals(""))
            conf.setSeason(season);
    });

    pack();
    setLocationRelativeTo(getOwner());
    setVisible(true);
}
}

The data is supposed to be saved to my configuration class which is a getter/setter class. I'm unable to retrieve any data unless I set it within the same class:

Main class:

public class Main {

public static void main(String[] args) {
    Configuration conf = new Configuration();

    //code for GUI not included but pretend the GUI is called here

    //data does not come out it's basically unset.
    System.out.println("Data from GUI: [season]"+ conf.getSeason()+ " Season expectations: " + conf.expectations());

    //yet this works just fine. 
    conf.setSeason("Summer");
    System.out.println("What's the last season set?: " + conf.getSeason()); 
}
}

Solution

  • Looks like you are creating two instances of your Configuration class. One in the GUI and one in your Main class. These are not shared.

    If you want to use the Configuration from the GUI try adding a getter for your Configuration within the GUI class

    public Configutation getConfig()
    {
         return conf;
    }
    

    then in your main try:

    public class Main {
    
        public static void main(String[] args) {
        //code for GUI not included but pretend the GUI is called here
        // Assuming something like:
        GUI gui = new GUI();
    
        Configuration conf = gui.getConfig();
    
        System.out.println("Data from GUI: [season]"+ conf.getSeason()+ " Season expectations: " + conf.expectations());
        }
    }
    

    Another option would be to create your Configuration as a Singleton - then you get the same instance rather then instantaiting a new one each time. Here is an example of how to do this