2017-06-15 87 views
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()); 
} 
} 

回答

2

看起來你正在創建你的Configuration類的兩個實例。一個在GUI中,另一個在Main類中。這些不共享。

如果你想使用ConfigurationGUI嘗試添加一個getter您ConfigurationGUI

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