简体   繁体   中英

How to save and load a listview in Javafx?

First off I am new to programming so please go easy on me since everything I have done up to this point is my first time doing it.

Basically I am trying to create an auto login program that will just enter a username and password into a website that I login into with multiple accounts everyday so instead of me always entering it I'm trying to make a program that will do that for me when I select a desired account and click run.

I used selenium and javafx to do all of this and everything works up until now where i have hit a brick wall for honestly a month now.

I can create an account and it adds it to a list but now what i want is to be able to save my listview somewhere and when the program starts up to be able to load it in again so that all of the previous accounts I have made are still there.

This is where I am stuck on, I have looked on all sorts of websites how to save it but none of them work for me since they use extra things like jQuery or some other stuff that I don't know how to use so if I could get some help with this problem that I am stuck on I would be very thankful.

I don't know if I need to post the code for my issue but I'll post how I created the Listviews and how the users are added.

If you feel like you could help me but need more info please notify me in the comments.

public class Controller {
    @FXML
    Button btnAdd, btnDelete, btnRun;
    @FXML
    public  ListView<String> userName;
    @FXML
    public ListView<String> listMail;
    @FXML
    public  ListView<String> listPass;
    @FXML
    private TextField txtUser;
    @FXML
    private TextField txtMail;
    @FXML
    private PasswordField txtPass;
@FXML
    void onButtonAdd(MouseEvent event) {
        if (txtUser.getText().trim().isEmpty() || txtMail.getText().trim().isEmpty() || txtPass.getText().trim().isEmpty()) {
             Alert fail= new Alert(AlertType.ERROR);
                fail.setHeaderText("Error");
                fail.setContentText("All fields must be entered");
                fail.showAndWait();
        }
         else {
            userName.getItems( ).add(txtUser.getText());
            listMail.getItems().add(txtMail.getText());
            listPass.getItems().add(txtPass.getText());     
    }
}

This app demos how to save data from a ListView to a text file and how to load data from a text file to a ListView . As stated in the other answer, there are other ways to store data. Example: database, CSV, TSV, Excel, JSON, etc. This answer may get more complicated if you take a different route. I like and recommend SQLite, JSON, TSV, or CSV.

Save ListView data using a Button

Button btnSave = new Button("Save");
btnSave.setOnAction((t) -> {
    try 
    {                
        saveFile.createNewFile();
        Files.write(saveFile.toPath(), listView.getItems().subList(0, listView.getItems().size()));
        getHostServices().showDocument(saveFile.getAbsolutePath());//Used to open the file the ListView info is saved to.
    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
    }            
});

Load Text file data to ListView

if(saveFile.exists())
{
    try 
    {
        List<String> linesLoadedFromFile = Files.readAllLines(saveFile.toPath());
        listView.getItems().addAll(linesLoadedFromFile);
    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
    }
}

Full Code

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class App extends Application
{

    public static void main(String[] args)
    {
        launch();
    }

    ListView<String> listView = new ListView();
    File saveFile = new File("save_here.txt");
    
    @Override
    public void start(Stage stage)
    {
        //Set the ListView cell factory. Add a Button to allow rows to be deleted for testing purposes.
        listView.setCellFactory((ListView<String> param) -> {
            Button btnDelete = new Button("Delete!");            
            
            final ListCell<String> cell = new ListCell<String>() {
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    setText(null);
                    setGraphic(null);
            
                    if (item != null || !empty) {
                        setText(item);
                        setGraphic(btnDelete);
                        btnDelete.setOnAction((t) -> {
                            getListView().getItems().remove(getItem());
                        });
                    }            
                }
            };
            
            return cell;
        });
        
        //Used to add text to the ListView
        TextField tfAdd = new TextField();
        Button btnAdd = new Button("Add");
        btnAdd.setOnAction((t) -> {
            if(tfAdd.getText().length() > 0)
            {
                listView.getItems().add(tfAdd.getText());
            }
        });
        
        //Used to save the current state of the ListView
        Button btnSave = new Button("Save");
        btnSave.setOnAction((t) -> {
            try 
            {                
                saveFile.createNewFile();
                Files.write(saveFile.toPath(), listView.getItems().subList(0, listView.getItems().size()));
                getHostServices().showDocument(saveFile.getAbsolutePath());//Used to open the file the ListView info is saved to.
            } 
            catch (IOException ex) 
            {
                ex.printStackTrace();
            }            
        });
    
        
        //Load file data to ListView
        if(saveFile.exists())
        {
            try 
            {
                List<String> linesLoadedFromFile = Files.readAllLines(saveFile.toPath());
                listView.getItems().addAll(linesLoadedFromFile);
            } 
            catch (IOException ex) 
            {
                ex.printStackTrace();
            }
        }
        
        HBox addRoot = new HBox(tfAdd, btnAdd);
        addRoot.setAlignment(Pos.CENTER);
        
        VBox root = new VBox(listView, addRoot, btnSave);
        root.setSpacing(3);
        root.setAlignment(Pos.CENTER);
        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();
    }
}

If you just want to save the data you can save your lists in a database or in a file as json objects.

If you decide to use a text file you can serialize the list to json and then put the 3 json objects you created (one per list) on separate lines in the file. When you re-open the program you read the file, read the rows and then transform the json objects back to the lists.

If you decide to use a database you first have to setup a database in your pc and then create a table with the various data you want to save.

Using the file alternative will cost you less time imho.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM