2017-06-15 9 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クラスです。私は同じクラス内に設定しない限り、私は、任意のデータを取得できませんよ:

メインクラス:あなたのConfigurationクラスの2つのインスタンスを作成しているよう

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

が見えます。 GUIに1つ、Mainに1つあります。これらは共有されていません。

あなたGUIクラス内Configuration

public Configutation getConfig() 
{ 
    return conf; 
} 

のgetterを追加GUI試してからConfigurationを使用したい場合は、あなたの主な試みで:

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

関連する問題