Welcome to Java Examples

Take a cup of tea and Let's Start programming

//notepad import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Scanner; import java.io.*; public class Notepad extends JFrame implements ActionListener { private TextArea textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY); private MenuBar menubar = new MenuBar(); private Menu file = new Menu(); private MenuItem openfile = new MenuItem(); private MenuItem savefile = new MenuItem(); private MenuItem close = new MenuItem(); public Notepad(){ this.setSize(500,500); this.setTitle("Java...Notepad Tutorial"); setDefaultCloseOperation(EXIT_ON_CLOSE); this.textarea.setFont(new Font("Century Gothic",Font.BOLD,12)); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(textarea); this.setMenuBar(this.menubar); this.menubar.add(this.file); this.file.setLabel("File"); this.openfile.setLabel("open"); this.openfile.addActionListener(this); this.file.add(this.openfile); this.savefile.setLabel("Save"); this.savefile.addActionListener(this); this.file.add(this.savefile); this.close.setLabel("Close"); this.close.addActionListener(this); this.file.add(close); } public void actionPerformed(ActionEvent e) { if(e.getSource()==close) { this.dispose(); } if(e.getSource()==openfile) { JFileChooser open = new JFileChooser(); int option = open.showOpenDialog(this); if(option == JFileChooser.APPROVE_OPTION) { this.textarea.setText(""); try{ Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath())); while(scan.hasNext()) this.textarea.append(scan.nextLine() +'\n'); } catch(Exception ex) { System.out.println(ex.getMessage()); } } } if(e.getSource()==savefile) { JFileChooser save = new JFileChooser(); int option = save.showSaveDialog(this); if(option == JFileChooser.APPROVE_OPTION) { try{ BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath())); out.write(this.textarea.getText()); out.close(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } } } public static void main(String args[]) { Notepad app = new Notepad(); app.setVisible(true); } }

Output

0 comments :

Post a Comment