0
我遇到了將數據從GUI傳遞到其他類的問題。一切都在GUI初始化,然後從那裏數據被傳遞到另一個類,其中附加的變化可能會發生:(簡體和缺失部分進行編譯)通過getter/setter將數據傳遞給其他類
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());
}
}