通过getter / setter

时间:2017-06-15 01:47:29

标签: java encapsulation getter-setter

我在将数据从GUI传递到其他类时遇到问题。所有内容都在GUI中初始化,然后从那里将数据传递到另一个可能发生其他更改的类:(编译的简化和缺失部分)

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

数据应该保存到我的配置类,这是一个getter / setter类。除非我在同一个类中设置它,否则我无法检索任何数据:

主要课程:

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

1 个答案:

答案 0 :(得分:2)

您似乎正在创建Configuration课程的两个实例。一个位于GUI,一个位于Main级。这些不是共享的。

如果您想使用Configuration中的GUI,请尝试在Configuration类中为GUI添加一个getter

public Configutation getConfig()
{
     return conf;
}

然后在你的主要尝试中:

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

另一种选择是将您的Configuration创建为单身人士 - 然后您获得相同的实例,而不是每次都提供一个新实例。 Here is an example of how to do this