View Javadoc
1   /*******************************************************************************
2    * Copyhacked (H) 2012-2025.
3    * This program and the accompanying materials
4    * are made available under no term at all, use it like
5    * you want, but share and discuss it
6    * every time possible with every body.
7    *
8    * Contributors:
9    *      ron190 at ymail dot com - initial implementation
10   *******************************************************************************/
11  package com.jsql.view.swing.list;
12  
13  import com.formdev.flatlaf.util.SystemFileChooser;
14  import com.jsql.util.I18nUtil;
15  import com.jsql.util.LogLevelUtil;
16  import com.jsql.view.swing.util.MediatorHelper;
17  import org.apache.logging.log4j.LogManager;
18  import org.apache.logging.log4j.Logger;
19  
20  import javax.swing.*;
21  import java.awt.event.ActionEvent;
22  import java.awt.event.ActionListener;
23  import java.io.FileOutputStream;
24  import java.io.IOException;
25  import java.io.PrintStream;
26  import java.nio.charset.StandardCharsets;
27  
28  /**
29   * Action to export a JList.
30   */
31  public class MenuActionExport implements ActionListener {
32      
33      private static final Logger LOGGER = LogManager.getRootLogger();
34  
35      /**
36       * List to export.
37       */
38      private final DnDList myList;
39      
40      /**
41       * Create action to export a list.
42       * @param myList List to export.
43       */
44      public MenuActionExport(DnDList myList) {
45          this.myList = myList;
46      }
47  
48      @Override
49      public void actionPerformed(ActionEvent actionEvent) {
50          final SystemFileChooser importFileDialog = new SystemFileChooser(MediatorHelper.model().getMediatorUtils().preferencesUtil().getPathFile());
51  
52          importFileDialog.setDialogTitle(I18nUtil.valueByKey("LIST_EXPORT_TITLE"));
53          int choice = importFileDialog.showSaveDialog(this.myList.getTopLevelAncestor());
54          if (choice != JFileChooser.APPROVE_OPTION) {
55              return;
56          }
57  
58          try (
59              var file = new FileOutputStream(importFileDialog.getSelectedFile());
60              var out = new PrintStream(file, false, StandardCharsets.UTF_8)
61          ) {
62              int len = this.myList.getModel().getSize();
63              for (var i = 0 ; i < len ; i++) {
64                  out.println(this.myList.getModel().getElementAt(i).toString());
65              }
66              LOGGER.log(LogLevelUtil.CONSOLE_SUCCESS, "List saved to {}", importFileDialog.getSelectedFile());
67          } catch (IOException e) {
68              LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
69          }
70      }
71  }