Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chp12;
- import java.awt.BorderLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.*;
- import java.util.*;
- import javax.swing.*;
- import javax.swing.JFrame;
- import javax.swing.JMenuBar;
- import javax.swing.JScrollPane;
- import javax.swing.JTextArea;
- public class TextFiles {
- public static void main (String [] args){
- NotepadFrame3 f=new NotepadFrame3();
- f.setVisible(true);
- }
- }
- class NotepadFrame3 extends JFrame{
- private static int WIDTH=600;
- private static int HEIGHT=600;
- public NotepadFrame3(){
- setSize(WIDTH, HEIGHT);
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- final JTextArea textArea=new JTextArea();
- JMenuBar menuBar=new JMenuBar();
- setJMenuBar(menuBar);
- JMenu fileMenu=new JMenu("File");
- menuBar.add(fileMenu);
- JMenuItem openMenuItem=new JMenuItem("Open...");
- fileMenu.add(openMenuItem);
- openMenuItem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- JFileChooser fileChooser=new JFileChooser();
- if(fileChooser.showDialog(NotepadFrame3.this, "Open")==JFileChooser.APPROVE_OPTION){
- File newFile=fileChooser.getSelectedFile();
- try(Scanner fileHandler=new Scanner (newFile)){
- textArea.setText("");
- while(fileHandler.hasNext()){
- String line=fileHandler.nextLine();
- textArea.append(line+"\n");
- }
- }catch (Exception exception){
- System.out.println ("Error");
- }
- }
- }
- });
- add(new JScrollPane(textArea), BorderLayout.CENTER);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment