Guest User

FileHandler

a guest
Mar 7th, 2015
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. package chp12;
  2. import java.awt.BorderLayout;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8. import javax.swing.JFrame;
  9. import javax.swing.JMenuBar;
  10. import javax.swing.JScrollPane;
  11. import javax.swing.JTextArea;
  12.  
  13. public class TextFiles {
  14.     public static void main (String [] args){
  15.         NotepadFrame3 f=new NotepadFrame3();
  16.         f.setVisible(true);
  17.     }
  18. }
  19.  
  20. class NotepadFrame3 extends JFrame{
  21.     private static int WIDTH=600;
  22.     private static int HEIGHT=600;
  23.    
  24.     public NotepadFrame3(){
  25.         setSize(WIDTH, HEIGHT);
  26.         setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  27.         final JTextArea textArea=new JTextArea();
  28.        
  29.         JMenuBar menuBar=new JMenuBar();
  30.         setJMenuBar(menuBar);
  31.         JMenu fileMenu=new JMenu("File");
  32.         menuBar.add(fileMenu);
  33.         JMenuItem openMenuItem=new JMenuItem("Open...");
  34.         fileMenu.add(openMenuItem);
  35.         openMenuItem.addActionListener(new ActionListener(){
  36.            public void actionPerformed(ActionEvent e){
  37.                JFileChooser fileChooser=new JFileChooser();
  38.                if(fileChooser.showDialog(NotepadFrame3.this, "Open")==JFileChooser.APPROVE_OPTION){
  39.                    File newFile=fileChooser.getSelectedFile();
  40.                    try(Scanner fileHandler=new Scanner (newFile)){
  41.                        textArea.setText("");
  42.                        while(fileHandler.hasNext()){
  43.                            String line=fileHandler.nextLine();
  44.                            textArea.append(line+"\n");
  45.                        }
  46.                    }catch (Exception exception){
  47.                        System.out.println ("Error");
  48.                    }
  49.                }
  50.            }
  51.         });
  52.         add(new JScrollPane(textArea), BorderLayout.CENTER);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment