JavaFX:列表在切换场景时清除值

时间:2018-12-21 21:23:04

标签: java list javafx arraylist

我有一个只要打开应用程序就应该存储的值列表。

我的应用程序中有2个场景,由两个不同的FXML文件控制。当我切换场景时,列表将清除其值。如何保存值?

问题可能是我没有打开一个全新的舞台吗?

我的代码:

package listManagerMain;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class ControllerOne {

// ******* Main Objects *******
    @FXML
    List<String> listNames = new ArrayList<String>();
    int x = 1;
    Boolean sceneSwap;

    // ******* Scene 1 Objects *******
    @FXML
    public Button buttonShow,buttonAdd;
    @FXML
    public Label labelSize,labelResponse,labelName; 
    @FXML
    public TextField textName;

    // ******* Scene 2 Objects*******
    @FXML
    public Button buttonMenu;
    @FXML
    public TextArea textList;

    // ******* Code Start *******
    public void switchScene(ActionEvent event) throws IOException {
        Parent root;
        Scene scene;
        Stage window;
        if(event.getSource() == buttonShow) {
            if(listNames.size() == 0)
                return;

            root = FXMLLoader.load(getClass().getResource("GuiTwo.fxml"));
            scene = new Scene(root);
            window = (Stage) ((Node)event.getSource()).getScene().getWindow();
            window.setScene(scene);
            sceneSwap = true;
            window.show();
        }
        if(event.getSource() == buttonMenu) {
            root = FXMLLoader.load(getClass().getResource("GuiOne.fxml"));
            scene = new Scene(root);
            window = (Stage) ((Node)event.getSource()).getScene().getWindow();
            window.setScene(scene);
            sceneSwap = false;
            window.show();
        }

        if(sceneSwap != false) {
            System.out.println(""); // Code here
        }
    }

    public void addName() {
        if(textName.getText().equals("")) {
            labelResponse.setText("Enter a name!");
            return;
        }

        String name = textName.getText();
        listNames.add("Name " + x + ": " + name);
        labelResponse.setText("'" + name + "' added to list...");
        textName.setText("");
        labelSize.setText("Size: " + x);
        x++;
    }
}

0 个答案:

没有答案