java Swing 将数据保存到指定文件中

java Swing 将数据保存到指定文件中。

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FileSaveAs {

	JFileChooser fileChooser = new JFileChooser();
	JTextField textField = new JTextField("输入文字");
	JButton button = new JButton("保存");
	JPanel panel = new JPanel();

	public FileSaveAs() {

		try {
			UIManager
					.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				saveDataToFile(textField.getText(), "my.txt");
			}

		});
		textField.setPreferredSize(new Dimension(200, 40));
		panel.add(textField);
		panel.add(button);

	}

	public void saveDataToFile(String data, String fileName) {

		fileChooser.setSelectedFile(new File(fileName));
		fileChooser.showSaveDialog(null);

		String filePath = fileChooser.getSelectedFile().toString();
		try {
			FileWriter writer = new FileWriter(filePath);
			writer.append(data);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		JFrame frame = new JFrame();

		frame.add(new FileSaveAs().panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// frame.setLocationRelativeTo(null);
		// frame.setLocationByPlatform(true);

		frame.pack();

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = frame.getSize();

		frame.setLocation((screenSize.width / 2 - frameSize.width / 2),
				(screenSize.height / 2 - frameSize.height / 2));
		frame.setVisible(true);
	}
}


 

你可能感兴趣的:(java)