如何将DefaultListModel中的数据附加到.txt文件

时间:2016-08-28 11:46:44

标签: java jframe

我已经为我的应用程序创建了一个DLM来保存我的jList的内容,这样我就可以将那些(type - >字符串)传递给.txt文件。但是,我所尝试的一切到目前为止还没有很好用为了进一步解释我的问题,我正在为一个后勤办公室创建一个小应用程序,它需要能够添加客户端,删除它们并按字母顺序或根据客户端的afm编号对它们进行排序。同时它也是如此。需要能够保存列表的客户端,然后当应用程序重新打开时,它必须使用.txt文件中的数据填充列表,该文件在用户单击save jMenu Button时创建/更新。我当前的问题是虽然我确实创建了.txt文件,但我只能将1行从模型追加到.txt文件中,如果我再次点击保存,它只会删除第一行中的先前数据并添加3个新字符串。基本上,我希望我的程序检查当我按Enter键时是否存在具有指定名称的.txt文件,然后:如果没有,则cre吃一个并附加所有当前客户端及其信息,否则如果是,只需将对列表(任何新客户端)所做的任何更改附加到.txt文件中。我在stackOverFlow上研究了很多并且在Oracle的文档上但没有找到解决我的问题的方法相当简单(我认为自己是java中的一个初学者,所以我在寻找最简单可行和最有效的方法解决这个问题的方法。)我希望你可以帮我解决任何提示或样本或链接。谢谢提前,这是我的两个班级:

ListModel.java

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ListModel extends JPanel {

  /**
 * 
 */
private static final long serialVersionUID = 1L;

  JList list;

  private DefaultListModel model;
  public FileManager fm = new FileManager();
  public String input,input2,input3;

  int counter;
  int selectedIndex;

  private ListModel() {

    setLayout(new BorderLayout());
    model = new DefaultListModel();
    list = new JList(model);

    JScrollPane pane = new JScrollPane(list);
    JButton addButton = new JButton("Add Client");
    JButton removeButton = new JButton("Remove Client");
   // model = new DefaultListModel();
    //model.addListDataListener(new ListModel());


    // add the client in the list
    addButton.addActionListener(new ActionListener() {

      @SuppressWarnings("unchecked") // for model.addElement

    public void actionPerformed(ActionEvent e) {
         input = JOptionPane.showInputDialog("Insert the client's   name:");
         input2 = JOptionPane.showInputDialog("Insert the client's last name:");
         input3 = JOptionPane.showInputDialog("Insert the client's afm:");

        model.addElement(input + " " + input2 + " " + "|" + "AFM : " + input3 + "| " + "Position: " + "(" + counter + ")");
        counter++;
        //System.out.println(model.get(counter));
      }
    });

    // Remove the client from the list at the selected index
    removeButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        //int position = 0;
        if (model.getSize() > 0)
          //position = Integer.parseInt(JOptionPane.showInputDialog( "Insert the client's  position in the list that you want to remove:"));
          //model.removeElementAt(position);
          //counter--;

        JOptionPane.showMessageDialog(null, "The client that you have selected will be removed!");  
         selectedIndex = list.getSelectedIndex();
         if(selectedIndex != -1) {
         model.remove(selectedIndex);
         JOptionPane.showMessageDialog(null, "Client has been successfully removed!");
      } else {
          JOptionPane.showMessageDialog(null, "Please choose a user to remove(if there is any).");
      }
     }
    });

    JMenuItem mntmSaveFile = new JMenuItem("Save File");
    mntmSaveFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            fm.openFile();
            fm.writeToFile(input, input2, input3);
            fm.closeFile();
            System.out.println("Listener method called!");
        }
    });

    // Creating the window using JFrame

    add(pane, BorderLayout.NORTH);

    JMenuBar menuBar = new JMenuBar();
    pane.setColumnHeaderView(menuBar);

    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);

    mnFile.add(mntmSaveFile);

    JMenuItem mntmExitApplication = new JMenuItem("Exit Application");
    mnFile.add(mntmExitApplication);

    JMenu mnClientOrder = new JMenu("Client Order");
    menuBar.add(mnClientOrder);

    JMenuItem mntmAlphabetically = new JMenuItem("Alphabetically");
    mnClientOrder.add(mntmAlphabetically);

    JMenuItem mntmAfmBased = new JMenuItem("AFM based");
    mnClientOrder.add(mntmAfmBased);
    add(addButton, BorderLayout.WEST);
    add(removeButton, BorderLayout.EAST);

    //System.out.println(dlm.capacity());
  }


public static void main(String[] args) {
   JFrame frame = new JFrame("LOGISTIKO GRAFIO");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new ListModel());
   frame.setSize(400, 230);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);

  }
  }

FileManager.java

import java.io.File;
import java.util.Formatter;

import javax.swing.JOptionPane;

public class FileManager {

File file = new File("ListArchive.txt");
private Formatter x;

public void openFile() {
    try {
        x = new Formatter("C:/Users/Stelios Papamichael/Desktop /Java/Runnable_Programs/LogisticOfficeApplication/ListArchive.txt");
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "File not saved!");
     } 
   }

   public void writeToFile(String name, String lastName , String afm) {     
        x.format("%s %s %s\n", name , lastName , afm );
        JOptionPane.showMessageDialog(null, "File saved!");
 }


public void closeFile() {
    x.close();
}

}

1 个答案:

答案 0 :(得分:0)

该帖子包含许多问题。为了使您更容易解决并更容易获得帮助,我建议您将其分解为较小的离散问题q问题,并为每个问题发布MCVE
以下是“较小”问题/问题/答案的一些例子:
您可以使用file.exists()检查文件是否存在
您可以使用file.createNewFile()

创建文件

用法示例:

if (!file.exists()) {
    file.createNewFile();
}

另见how to append data to a file