나는 (형식 -> 문자열)을 .txt 파일로 전달할 수 있도록 내 jList의 내용을 보유 할 응용 프로그램 용 DLM을 만들었습니다. 내가 시도한 모든 것은 아직까지는 잘 작동하지 않았다. 문제를 조금 더 설명하기 위해 나는 클라이언트를 추가하고, 제거하고, 사전 순으로 또는 그들을 기반으로 정렬 할 수있는 물류 사무소를위한 작은 응용 프로그램을 만들고있다. 또한 클라이언트의 afm 번호가 필요합니다. 또한 목록의 클라이언트를 저장할 수 있어야하고 응용 프로그램이 다시 열리면 사용자가 jMenu 저장을 클릭 할 때 생성되거나 업데이트되는 .txt 파일 내의 데이터를 사용하여 목록을 채워야합니다 Button.My 현재 문제는 .txt 파일을 만들지 만 모델에서 .txt 파일로 한 줄만 추가 할 수 있으며 다시 저장하면 첫 번째 줄에서 이전 데이터가 삭제되고 3이 추가됩니다. 새로운 스트라이프 ngs.Basically, 내 프로그램이 원하는 이름을 가진 .txt 파일이 있는지 확인하기를 원한다면 입력을 누른 다음 : 만약 아니라면 하나를 만들고 모든 현재 클라이언트와 정보를 추가한다. 그렇지 않으면 변경 사항을 추가한다. stackOverFlow와 오라클의 문서에서 꽤 많이 연구되었지만 제 문제에 대한 해결책을 찾지 못했습니다. (매우 간단합니다. 자바에서 beginginer라고 생각합니다. 나는이 문제를 해결하는 가장 쉬운 방법과 가장 효율적인 방법을 찾고있다.) 당신이 어떤 힌트 나 샘플 또는 링크로도 나를 도울 수 있기를 바랍니다. 사전에 감사드립니다. 내 두 클래스 :DefaultListModel의 데이터를 .txt 파일에 추가하는 방법
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();
}
}
참조 http://stackoverflow.com/help/someone-answers – c0der