• (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

Creating a basic Notepad Application Rate Topic: ***** 6 Votes

#1 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1383
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 05 October 2008 - 08:17 AM

*
POPULAR

Creating a basic notepad app

What do I already need to know in order to follow this tutorial?
Not a lot, actually. This stuff is a lot easier than people tend to make it look. My aim is to show you how simple it is to harness the power of Java. Just so long as you've got a basic grasp of the stuff, you should be able to take it in.

So what am I going to learn?
Hopefully, quite a bit! In this tutorial, I'm going to cover the basics of:
  • Multiple inheritance (very basic explanation)
  • GUI design
  • Event handling
  • File input/output
  • Exception handling
Just to get your mouth watering, here's a screenshot of what we'll be making:
http://www.dreamincode.net/forums/index.php?act=Attach&type=post&id=8512
Isn't it sexy? :wub:

So, to get started, we need to import a few things, namely:
import javax.swing.*; // for the main JFrame design
import java.awt.*; // for the GUI stuff
import java.awt.event.*; // for the event handling
import java.util.Scanner; // for reading from a file
import java.io.*; // for writing to a file


Next, let's go over multiple inheritance. Our notepad app is going to have the appearance of a JFrame, and the functionality of an ActionListener.

So, we're going to extend JFrame, and implement ActionListener. Makes sense, right?

public class Notepad extends JFrame implements ActionListener {
w00t!

Now we're going to set up our basic stuff. The classes that we'll be using for the design are:
  • TextArea
  • MenuBar
  • Menu
  • MenuItem
So, let's go over it:

The TextArea The most important bit, right?
This is the area of text that the user can write in. You'd never guess that, would you?!

So, the constructor for our TextArea is quite big~ it accepts quite a few parameters.
 private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);

Let's break it down.
First, we pass "" which is basically an empty string. The constructor is looking for the text to put in the TextArea initially, so you could pass "poo" and the TextArea would say poo when you launch the app.
Next, we have the size. 0,0 (Height/Width)
This might seem weird~ we're setting it to be 0x0 pixels, so it won't be visible, right? Wrong. The basic GUI design in Java will automatically set the TextArea to fill the window. In other words, we don't have to worry about it.
TextArea.SCROLLBARS_VERTICAL_ONLY adds WordWrap to our application, to make it look neater. Times where you shouldn't have WordWrap include code views (it all belongs on one line)

The MenuBar
Much simpler, the code speaks for itself:
        private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
	private Menu file = new Menu(); // our File menu
	// what's going in File? let's see...
	private MenuItem openFile = new MenuItem();  // an open option
	private MenuItem saveFile = new MenuItem(); // a save option
	private MenuItem close = new MenuItem(); // and a close option!


On to the constructor!
Personally, I find it easier to go along code when it's together. So, I've added enough comments in to the constructor code for it to make sense:
	public Notepad() {
		this.setSize(500, 300); // set the initial size of the window
		this.setTitle("Java Notepad Tutorial"); // set the title of the window
		setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
		this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
		// this is why we didn't have to worry about the size of the TextArea!
		this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
		this.getContentPane().add(textArea);

		// add our menu bar into the GUI
		this.setMenuBar(this.menuBar);
		this.menuBar.add(this.file); // we'll configure this later
		
		// first off, the design of the menuBar itself. Pretty simple, all we need to do
		// is add a couple of menus, which will be populated later on
		this.file.setLabel("File");
		
		// now it's time to work with the menu. I'm only going to add a basic File menu
		// but you could add more!
		
		// now we can start working on the content of the menu~ this gets a little repetitive,
		// so please bare with me!
		
		// time for the repetitive stuff. let's add the "Open" option
		this.openFile.setLabel("Open"); // set the label of the menu item
		this.openFile.addActionListener(this); // add an action listener (so we know when it's been clicked
		this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false)); // set a keyboard shortcut
		this.file.add(this.openFile); // add it to the "File" menu
		
		// and the save...
		this.saveFile.setLabel("Save");
		this.saveFile.addActionListener(this);
		this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
		this.file.add(this.saveFile);
		
		// and finally, the close option
		this.close.setLabel("Close");
		// along with our "CTRL+F4" shortcut to close the window, we also have
		// the default closer, as stated at the beginning of this tutorial.
		// this means that we actually have TWO shortcuts to close:
		// 1) the default close operation (example, Alt+F4 on Windows)
		// 2) CTRL+F4, which we are about to define now: (this one will appear in the label)
		this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
		this.close.addActionListener(this);
		this.file.add(this.close);
	}


See? That wasn't so bad now, was it? I told you this stuff is easy~ it's just a little repetitive at times.

Listening for Events
Remember how I said earlier that we implement ActionListener? Well, now it's time to learn about events. Because we're implementing ActionListener, we can have a function called ActionPerformed() which will listen for events for us. Neat, huh? Again, I've added plenty of comments so you can see what's happening along the way.
NOTE: This section will also cover the basics of file I/O, and the use of JFileChooser
	public void actionPerformed (ActionEvent e) {
		// if the source of the event was our "close" option
		if (e.getSource() == this.close)
			this.dispose(); // dispose all resources and close the application
		
		// if the source was the "open" option
		else if (e.getSource() == this.openFile) {
			JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open)
			int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)
			// NOTE: because we are OPENing a file, we call showOpenDialog~
			// if the user clicked OK, we have "APPROVE_OPTION"
			// so we want to open the file
			if (option == JFileChooser.APPROVE_OPTION) {
				this.textArea.setText(""); // clear the TextArea before applying the file contents
				try {
					// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
					Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
					while (scan.hasNext()) // while there's still something to read
						this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
				} catch (Exception ex) { // catch any exceptions, and...
					// ...write to the debug console
					System.out.println(ex.getMessage());
				}
			}
		}
		
		// and lastly, if the source of the event was the "save" option
		else if (e.getSource() == this.saveFile) {
			JFileChooser save = new JFileChooser(); // again, open a file chooser
			int option = save.showSaveDialog(this); // similar to the open file, only this time we call
			// showSaveDialog instead of showOpenDialog
			// if the user clicked OK (and not cancel)
			if (option == JFileChooser.APPROVE_OPTION) {
				try {
					// create a buffered writer to write to a file
					BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
					out.write(this.textArea.getText()); // write the contents of the TextArea to the file
					out.close(); // close the file stream
				} catch (Exception ex) { // again, catch any exceptions and...
					// ...write to the debug console
					System.out.println(ex.getMessage());
				}
			}
		}
	}


Oh, and don't forget to close off the class! }

So, you should now have a basic Notepad app!

As with all my other tutorials, I'll post the complete code, in case you got lost along the way:

THE FINAL PRODUCT!
import javax.swing.*;
import java.awt.*;
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(); // first, create a MenuBar item
	private Menu file = new Menu(); // our File menu
	// what's going in File? let's see...
	private MenuItem openFile = new MenuItem();  // an open option
	private MenuItem saveFile = new MenuItem(); // a save option
	private MenuItem close = new MenuItem(); // and a close option!
	
	public Notepad() {
		this.setSize(500, 300); // set the initial size of the window
		this.setTitle("Java Notepad Tutorial"); // set the title of the window
		setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
		this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
		// this is why we didn't have to worry about the size of the TextArea!
		this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
		this.getContentPane().add(textArea);

		// add our menu bar into the GUI
		this.setMenuBar(this.menuBar);
		this.menuBar.add(this.file); // we'll configure this later
		
		// first off, the design of the menuBar itself. Pretty simple, all we need to do
		// is add a couple of menus, which will be populated later on
		this.file.setLabel("File");
		
		// now it's time to work with the menu. I'm only going to add a basic File menu
		// but you could add more!
		
		// now we can start working on the content of the menu~ this gets a little repetitive,
		// so please bare with me!
		
		// time for the repetitive stuff. let's add the "Open" option
		this.openFile.setLabel("Open"); // set the label of the menu item
		this.openFile.addActionListener(this); // add an action listener (so we know when it's been clicked
		this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false)); // set a keyboard shortcut
		this.file.add(this.openFile); // add it to the "File" menu
		
		// and the save...
		this.saveFile.setLabel("Save");
		this.saveFile.addActionListener(this);
		this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
		this.file.add(this.saveFile);
		
		// and finally, the close option
		this.close.setLabel("Close");
		// along with our "CTRL+F4" shortcut to close the window, we also have
		// the default closer, as stated at the beginning of this tutorial.
		// this means that we actually have TWO shortcuts to close:
		// 1) the default close operation (example, Alt+F4 on Windows)
		// 2) CTRL+F4, which we are about to define now: (this one will appear in the label)
		this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
		this.close.addActionListener(this);
		this.file.add(this.close);
	}
	
	public void actionPerformed (ActionEvent e) {
		// if the source of the event was our "close" option
		if (e.getSource() == this.close)
			this.dispose(); // dispose all resources and close the application
		
		// if the source was the "open" option
		else if (e.getSource() == this.openFile) {
			JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open)
			int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)
			// NOTE: because we are OPENing a file, we call showOpenDialog~
			// if the user clicked OK, we have "APPROVE_OPTION"
			// so we want to open the file
			if (option == JFileChooser.APPROVE_OPTION) {
				this.textArea.setText(""); // clear the TextArea before applying the file contents
				try {
					// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
					Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
					while (scan.hasNext()) // while there's still something to read
						this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
				} catch (Exception ex) { // catch any exceptions, and...
					// ...write to the debug console
					System.out.println(ex.getMessage());
				}
			}
		}
		
		// and lastly, if the source of the event was the "save" option
		else if (e.getSource() == this.saveFile) {
			JFileChooser save = new JFileChooser(); // again, open a file chooser
			int option = save.showSaveDialog(this); // similar to the open file, only this time we call
			// showSaveDialog instead of showOpenDialog
			// if the user clicked OK (and not cancel)
			if (option == JFileChooser.APPROVE_OPTION) {
				try {
					// create a buffered writer to write to a file
					BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
					out.write(this.textArea.getText()); // write the contents of the TextArea to the file
					out.close(); // close the file stream
				} catch (Exception ex) { // again, catch any exceptions and...
					// ...write to the debug console
					System.out.println(ex.getMessage());
				}
			}
		}
	}
    // the main method, for actually creating our notepad and setting it to visible.
    public static void main(String args[]) {
        Notepad app = new Notepad();
        app.setVisible(true);
}
}


Happy coding!

Attached image(s)

  • Attached Image


Is This A Good Question/Topic? 14
  • +

Replies To: Creating a basic Notepad Application

#2 Locke  Icon User is offline

  • Sarcasm Extraordinaire!
  • member icon

Reputation: 521
  • View blog
  • Posts: 5,596
  • Joined: 20-March 08

Posted 05 October 2008 - 08:55 AM

Nice tutorial! :^:
Was This Post Helpful? 0
  • +
  • -

#3 ran123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 02-December 08

Posted 02 December 2008 - 11:16 AM

How do I run this notepad program. I tried adding the main method and then creating an instance of it, but nothing happened.
Was This Post Helpful? 0
  • +
  • -

#4 skywalkno8  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 07-December 08

Posted 07 December 2008 - 11:15 PM

actually i did the same but no action at all..
n how do i place the main method n wat should i put into main method..please!!
Was This Post Helpful? 0
  • +
  • -

#5 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1383
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 08 December 2008 - 11:25 AM

:blush: My bad~!

I musta been busy that day. All you need to do is add a function called "main" into your class, and away you go! :)

public static void main(String args[]) {
     Notepad app = new Notepad();
     app.setVisible(true);
}

Was This Post Helpful? 0
  • +
  • -

#6 skywalkno8  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 07-December 08

Posted 09 December 2008 - 12:30 AM

halo guys.. i do have a questioned here how do i created and set font list on a default application..
Was This Post Helpful? 0
  • +
  • -

#7 Ostralis  Icon User is offline

  • #include <greeter>
  • member icon

Reputation: 9
  • View blog
  • Posts: 559
  • Joined: 13-December 08

Posted 13 December 2008 - 01:29 PM

The tutorial looks good, I'll definitely have a go at it and thanks for sharing! This will help bunches!
Was This Post Helpful? 0
  • +
  • -

#8 sama_thebest  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 2
  • Joined: 16-December 08

Posted 16 December 2008 - 10:18 PM

very very nice :^: :^: :^: :^:
Was This Post Helpful? 0
  • +
  • -

#9 5thWall  Icon User is offline

  • Occasional Member

Reputation: 31
  • View blog
  • Posts: 530
  • Joined: 17-September 08

Posted 18 December 2008 - 10:14 PM

Thanks! We haven't done anything with Java Swing in any of my classes so far. :huh: So I've been looking for tutorials to get into it with. One question though? What's with all the this.whatever? Is there a specific reason you do that? I took them all out and my code works fine.
Was This Post Helpful? 0
  • +
  • -

#10 bastones  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 35
  • Joined: 03-January 09

Posted 13 January 2009 - 05:07 PM

View Post5thWall, on 18 Dec, 2008 - 09:14 PM, said:

Thanks! We haven't done anything with Java Swing in any of my classes so far. :huh: So I've been looking for tutorials to get into it with. One question though? What's with all the this.whatever? Is there a specific reason you do that? I took them all out and my code works fine.


The this keyword refers to the fields (i.e. the variables at the start of the code) such as:

  private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
	 private Menu file = new Menu(); // our File menu
	 // what's going in File? let's see...
	 private MenuItem openFile = new MenuItem();  // an open option
	 private MenuItem saveFile = new MenuItem(); // a save option
	 private MenuItem close = new MenuItem(); // and a close option!


So to refer to these in the constructor we use this.fieldName - variables that are not inside methods or constructors are called fields. Because in this tutorial it is extending (inheriting) JFrame the this.setSize, etc., is referring to the setSize method of the JFrame class.
Was This Post Helpful? 0
  • +
  • -

#11 5thWall  Icon User is offline

  • Occasional Member

Reputation: 31
  • View blog
  • Posts: 530
  • Joined: 17-September 08

Posted 13 January 2009 - 06:48 PM

Thanks bastones, but I know what the this keyword does. ;) I've only seen it used when someone names a method argument the same as an object level variable. Like so:
private int A;
private int B;

//We use the name A twice so we use 'this' to tell them apart.
public setA(int A) {
  this.A = A;
}

//The name B is only used once so we don't need 'this' here.
public setB(int _B)/> {
  B = _B;
}



So I was wondering if there was a special reason why you would use this elsewhere while writing for Swing.

This post has been edited by 5thWall: 13 January 2009 - 10:41 PM

Was This Post Helpful? 0
  • +
  • -

#12 bastones  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 35
  • Joined: 03-January 09

Posted 14 January 2009 - 11:21 AM

View Post5thWall, on 13 Jan, 2009 - 05:48 PM, said:

Thanks bastones, but I know what the this keyword does. ;) I've only seen it used when someone names a method argument the same as an object level variable. Like so:
private int A;
private int B;

//We use the name A twice so we use 'this' to tell them apart.
public setA(int A) {
  this.A = A;
}

//The name B is only used once so we don't need 'this' here.
public setB(int _B)/> {
  B = _B;
}



So I was wondering if there was a special reason why you would use this elsewhere while writing for Swing.


Well that's exactly why you'd use the this keyword, incase there are paramater variables that are the same name as your fields names. You can still call your fields via its actual name too under those conditions. Take a look here for a quick overview of the keyword because there are a few more uses for it.
Was This Post Helpful? 0
  • +
  • -

#13 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1383
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 18 January 2009 - 09:34 AM

Sorry about the late response~!

Quote

halo guys.. i do have a questioned here how do i created and set font list on a default application..

I actually have a snippet for a "font dialog" class.

http://www.dreaminco...snippet2571.htm

Enjoy~! :)
Was This Post Helpful? 0
  • +
  • -

#14 joezim007  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 110
  • Joined: 13-September 08

Posted 23 January 2009 - 09:46 AM

View Postbastones, on 13 Jan, 2009 - 05:07 PM, said:

View Post5thWall, on 18 Dec, 2008 - 09:14 PM, said:

Thanks! We haven't done anything with Java Swing in any of my classes so far. :huh: So I've been looking for tutorials to get into it with. One question though? What's with all the this.whatever? Is there a specific reason you do that? I took them all out and my code works fine.


The this keyword refers to the fields (i.e. the variables at the start of the code) such as:

  private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
	 private Menu file = new Menu(); // our File menu
	 // what's going in File? let's see...
	 private MenuItem openFile = new MenuItem();  // an open option
	 private MenuItem saveFile = new MenuItem(); // a save option
	 private MenuItem close = new MenuItem(); // and a close option!


So to refer to these in the constructor we use this.fieldName - variables that are not inside methods or constructors are called fields. Because in this tutorial it is extending (inheriting) JFrame the this.setSize, etc., is referring to the setSize method of the JFrame class.

I was wondering about this too. Seems kinda pointless and redundant to use "this" all the time.
Was This Post Helpful? 1
  • +
  • -

#15 joezim007  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 110
  • Joined: 13-September 08

Posted 24 January 2009 - 12:49 PM

I was wondering if you had any reasons for using TextArea, MenuBar, Menu, and MenuItem over the JTextArea, JMenuBar, JMenu, and JMenuItem alternatives? Are there any downsides to the J components?
Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »