package fileio; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; public class Notepad extends JFrame { JTextArea text = new JTextArea(); JMenuItem fileOpen = new JMenuItem("Open"); class Opener implements ActionListener { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Text and Source code", "txt", "java"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); read(file); } } } public Notepad() { super("Notepad"); getContentPane().setLayout(new BorderLayout()); getContentPane().add(new JScrollPane(text)); JMenu file = new JMenu("File"); file.add(fileOpen); JMenuBar bar = new JMenuBar(); bar.add(file); setJMenuBar(bar); fileOpen.addActionListener(new Opener()); setSize(500,400); setVisible(true); } private void read(File name) { try { FileReader fr = new FileReader(name); BufferedReader in = new BufferedReader(fr); String line = in.readLine(); while (line != null) { text.append(line + "\n"); line = in.readLine(); } in.close(); fr.close(); } catch(IOException e) { JOptionPane.showMessageDialog(this, "ERROR: " + e); } } public static void main(String args[]) { Notepad n = new Notepad(); } }