Java 99. Cách mở file hoặc lưu file trong Java Swing



    Bản quyền thuộc về TITV.vn, 
    vui lòng không đăng tải lại nội dung từ trang này.

    Video giải thích chi tiết


     Code chi tiết 

    
    package model;
    
    public class MyNotepadModel {
    	private String fileName;
    	private String content;
    	
    	public MyNotepadModel() {
    		this.fileName = "";
    		this.content = "";
    	}
    	public String getFileName() {
    		return fileName;
    	}
    	public void setFileName(String fileName) {
    		this.fileName = fileName;
    	}
    	public String getContent() {
    		return content;
    	}
    	public void setContent(String content) {
    		this.content = content;
    	}
    	
    	
    }
    
    
    
    package view;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    
    import controller.MyNotepadController;
    import model.MyNotepadModel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import java.awt.Font;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    
    public class MyNotepadView extends JFrame {
    
    	private JPanel contentPane;
    	public MyNotepadModel model;
    	public JLabel lblNewLabel;
    	public JTextArea textArea; 
    
    	/**
    	 * Launch the application.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					MyNotepadView frame = new MyNotepadView();
    					frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the frame.
    	 */
    	public MyNotepadView() {
    		this.model = new MyNotepadModel();
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(100, 100, 689, 475);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(new BorderLayout(0, 0));
    		
    		textArea = new JTextArea();
    		textArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
    
    		JScrollPane scrollPane = new JScrollPane(textArea);
    		contentPane.add(scrollPane, BorderLayout.CENTER);
    		
    		JPanel panel = new JPanel();
    		panel.setPreferredSize(new Dimension(10, 50));
    		contentPane.add(panel, BorderLayout.SOUTH);
    		panel.setLayout(null);
    		
    		lblNewLabel = new JLabel("New label");
    		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
    		lblNewLabel.setBounds(10, 0, 314, 39);
    		panel.add(lblNewLabel);
    		
    		ActionListener action = new MyNotepadController(this);
    		
    		JButton btnOpen = new JButton("Open");
    		btnOpen.addActionListener(action);
    		btnOpen.setFont(new Font("Tahoma", Font.PLAIN, 18));
    		btnOpen.setBounds(398, 11, 89, 28);
    		panel.add(btnOpen);
    		
    		JButton btnSave = new JButton("Save");
    		btnSave.addActionListener(action);
    		btnSave.setFont(new Font("Tahoma", Font.PLAIN, 18));
    		btnSave.setBounds(497, 11, 89, 28);
    		panel.add(btnSave);
    		this.setVisible(true);
    	}
    }
    
    
    
    package controller;
    
    import java.awt.event.ActionEvent;
    import java.beans.PropertyChangeListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.util.List;
    
    import javax.swing.Action;
    import javax.swing.JFileChooser;
    
    import view.MyNotepadView;
    
    import java.awt.event.ActionListener;
    
    public class MyNotepadController implements ActionListener {
    	MyNotepadView myNotepadView;
    
    	public MyNotepadController(MyNotepadView myNotepadView) {
    		this.myNotepadView = myNotepadView;
    	}
    
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		String command = e.getActionCommand();
    		JFileChooser fc = new JFileChooser();
    		
    		if (command.equals("Open")) {
    			int returnVal = fc.showOpenDialog(this.myNotepadView);
    			if (returnVal == JFileChooser.APPROVE_OPTION) {
    				File file = fc.getSelectedFile();
    				String fileName = file.getName();
    				this.myNotepadView.model.setFileName(file.getAbsolutePath());
    				this.myNotepadView.lblNewLabel.setText(this.myNotepadView.model.getFileName());
    				if(fileName.endsWith(".txt")) {
    					try {
    						List<String> allText = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
    						String result = "";
    						for (String line : allText) {
    							result+=line;
    							result+="\n";
    						}
    						this.myNotepadView.model.setContent(result);
    						this.myNotepadView.textArea.setText(this.myNotepadView.model.getContent());
    					} catch (Exception e1) {
    						e1.printStackTrace();
    					}
    				}
    			} 
    		} else if (command.equals("Save")) {
    			if(this.myNotepadView.model.getFileName().length()>0) {
    				save(this.myNotepadView.model.getFileName());
    			}else {
    				int returnVal = fc.showSaveDialog(this.myNotepadView);
    				if (returnVal == JFileChooser.APPROVE_OPTION) {
    					File file = fc.getSelectedFile();
    					save(file.getAbsolutePath());
    				} 
    			}
    		}
    	}
    	public void save(String fileName) {
    		try {
    			PrintWriter pw = new PrintWriter(fileName, "UTF-8");
    			String data = this.myNotepadView.textArea.getText();
    			pw.print(data);
    			pw.flush();
    			pw.close();
    		} catch (FileNotFoundException e1) {
    			e1.printStackTrace();
    		} catch (UnsupportedEncodingException e1) {
    			e1.printStackTrace();
    		}
    	}
    }
    
    
    
    package test;
    
    import javax.swing.UIManager;
    
    import view.MyNotepadView;
    
    public class Test {
    	public static void main(String[] args) {
    		try {
    			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    			new MyNotepadView();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    

    Không có nhận xét nào:

    Đăng nhận xét