Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

Dream.In.Code> Programming Tutorials> Java Tutorials


(4 Pages)

1
2
3

Last
Creating a basic Notepad Application Rate Topic: 7 Votes Follow & Share General Discussion
gabehabe Caffeine Lounge
Posted 05 October 2008 - 08:17 AM
Corner Cubicle

Student Campus
POPULAR
Creating a basic notepad app Software Development
What do I already need to know in order to follow this
tutorial? Industry News
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 Introduce Yourself
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. Nightmare.In.Code

So what am I going to learn? Java Tutorials


Hopefully, quite a bit! In this tutorial, I'm going to cover the
basics of: I need help with this Programming Help
Multiple inheritance (very basic explanation)
GUI design Array Question
Event handling C and C++
File input/output Dijkstra's Algorithm
Exception handling VB.NET
Just to get your mouth watering, here's a screenshot of Book Review: Murach's
what we'll be making: Java
http://www.dreamincode.net/forums Beginning Java with
/index.php?act=Attach&type=post&id=8512 C#
Isn't it sexy? :wub: NetBeans
Python
So, to get started, we need to import a few things, namely: Graph Data Structure PHP
1 import javax.swing.*; // for the main JFrame Tutorial
Mobile Development
design
Swing, Passive Model- ASP.NET
2 import java.awt.*; // for the GUI stuff
3 import java.awt.event.*; // for the event View-Presenter in 5
.NET Framework
handling minutes.
4 import java.util.Scanner; // for reading from a Ruby
file Book Review: Murach's
Game Development
5 import java.io.*; // for writing to a file Java Servlets and JSP
Assembly
Phobos - A JavaFX
Databases
Next, let's go over multiple inheritance. Our notepad app is Games Engine: Part 2 -
going to have the appearance of a JFrame, and the ColdFusion
functionality of an ActionListener. JavaFX Scene API and
VB6
the FSM
So, we're going to extend JFrame, and implement
ActionListener. Makes sense, right? Other Languages
Maven Tutorial 2 -
52 Weeks Of Code
Adding Dependencies
1 public class Notepad extends JFrame implements
ActionListener { Maven Tutorial 1 -
Installation and Getting Web Development
w00t!
Started Web Development
Now we're going to set up our basic stuff. The classes that
we'll be using for the design are:
TextArea Phobos - A JavaFX HTML & CSS
MenuBar Games Engine: Part 1 -
Menu JavaScript
MenuItem Intro to Threading and
So, let's go over it:

1 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

DP
The TextArea The most important bit, right? Graphic Design
This is the area of text that the user can write in. You'd
never guess that, would you?! 221 More Java Flash & ActionScript
FAQ | Team Blog | Feedback/Support | Advertising | Terms of Use |Blogging
Tutorials... Privacy Policy |
So, the constructor for our TextArea is quite big~ it accepts
quite a few parameters. About Us
SEO & Advertising
1 private TextArea textArea = new TextArea("", Reference Sheets Web Servers & Hosting
0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
Copyright 2001-2017 MediaGroup1 LLC, All Rights ReservedSite Check

Let's break it down. A MediaGroup1 LLC Production - Version 6.0.2.1.36


First, we pass "" which is basically an empty string.Server:
The
constructor is looking for the text to put in the TextArea
secure3
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)
Code Snippets
C Snippets
The MenuBar
Much simpler, the code speaks for itself:
C++ Snippets
1 private MenuBar menuBar = new MenuBar(); //
Java Snippets
first, create a MenuBar item
2 private Menu file = new Menu(); // our File menu Visual Basic Snippets
3 // what's going in File? let's see...
4 private MenuItem openFile = new MenuItem(); // C# Snippets
an open option VB.NET Snippets
5 private MenuItem saveFile = new MenuItem(); // a
save option ASP.NET Snippets
6 private MenuItem close = new MenuItem(); // and
PHP Snippets
a close option!
Python Snippets

Ruby Snippets
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 ColdFusion Snippets
constructor code for it to make sense:
SQL Snippets
01 public Notepad() {
02 this.setSize(500, 300); // set the initial Assembly Snippets
size of the window Functional
03 this.setTitle("Java Notepad Tutorial"); //
set the title of the window Programming Snippets
04 setDefaultCloseOperation(EXIT_ON_CLOSE); // Perl Snippets
set the default close operation (exit when it
gets closed) HTML/CSS Snippets
05 this.textArea.setFont(new Font("Century
Javascript Snippets
Gothic", Font.BOLD, 12)); // set a default font
for the TextArea Flash/ActionScript
06 // this is why we didn't have to worry about
Snippets
the size of the TextArea!
07 this.getContentPane().setLayout(new ASP Snippets
BorderLayout()); // the BorderLayout bit makes
it fill it automatically Linux, Unix, and Bash
08 this.getContentPane().add(textArea); Snippets
09
10 // add our menu bar into the GUI
Other Languages
11 this.setMenuBar(this.menuBar); Snippets
12 this.menuBar.add(this.file); // we'll
Regex
configure this later
13
14 // first off, the design of the menuBar DIC Chatroom

2 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

itself. Pretty simple, all we need to do


Join our IRC Chat
15 // is add a couple of menus, which will be
populated later on
16 this.file.setLabel("File"); Bye Bye Ads
17
18 // now it's time to work with the menu. I'm
only going to add a basic File menu
19 // but you could add more!
20
21 // now we can start working on the content

Secure Connection
of the menu~ this gets a little repetitive,
22 // so please bare with me!
23

Failed
24 // time for the repetitive stuff. let's add
the "Open" option
25 this.openFile.setLabel("Open"); // set the
label of the menu item
26 this.openFile.addActionListener(this); //
add an action listener (so we know when it's
been clicked
27 this.openFile.setShortcut(new The connection to the server was reset while
MenuShortcut(KeyEvent.VK_O, false)); // set a
the page was loading.
keyboard shortcut

The page you are trying to view cannot be


28 this.file.add(this.openFile); // add it to
the "File" menu
29 shown because the authenticity of the
30 // and the save...
31 this.saveFile.setLabel("Save");
32 this.saveFile.addActionListener(this);
33 this.saveFile.setShortcut(new
MenuShortcut(KeyEvent.VK_S, false));
34 this.file.add(this.saveFile);
35

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

01 public void actionPerformed (ActionEvent e) {


02 // if the source of the event was our
"close" option
03 if (e.getSource() == this.close)
04 this.dispose(); // dispose all resources
and close the application
05
06 // if the source was the "open" option
07 else if (e.getSource() == this.openFile) {
08 JFileChooser open = new JFileChooser();
// open up a file chooser (a dialog for the user
to browse files to open)
09 int option = open.showOpenDialog(this);
// get the option that the user selected
(approve or cancel)
10 // NOTE: because we are OPENing a file,
we call showOpenDialog~
11 // if the user clicked OK, we have
"APPROVE_OPTION"

3 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

12 // so we want to open the file


13 if (option ==
JFileChooser.APPROVE_OPTION) {
14 this.textArea.setText(""); // clear
the TextArea before applying the file contents
15 try {
16 // create a scanner to read the
file (getSelectedFile().getPath() will get the
path to the file)
17 Scanner scan = new Scanner(new
FileReader(open.getSelectedFile().getPath()));
18 while (scan.hasNext()) // while
there's still something to read
19 this.textArea.append(scan.nextLine()
+ "\n"); // append the line to the TextArea
20 } catch (Exception ex) { // catch
any exceptions, and...
21 // ...write to the debug console
22 System.out.println(ex.getMessage());
23 }
24 }
25 }
26
27 // and lastly, if the source of the event
was the "save" option
28 else if (e.getSource() == this.saveFile) {
29 JFileChooser save = new JFileChooser();
// again, open a file chooser
30 int option = save.showSaveDialog(this);
// similar to the open file, only this time we
call
31 // showSaveDialog instead of
showOpenDialog

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!


001 import javax.swing.*;
002 import java.awt.*;
003 import java.awt.event.*;
004 import java.util.Scanner;
005 import java.io.*;
006
007 public class Notepad extends JFrame implements
ActionListener {
008 private TextArea textArea = new TextArea("",
0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
009 private MenuBar menuBar = new MenuBar(); //
first, create a MenuBar item
010 private Menu file = new Menu(); // our File
menu
011 // what's going in File? let's see...
012 private MenuItem openFile = new MenuItem();
// an open option
013 private MenuItem saveFile = new MenuItem();
// a save option
014 private MenuItem close = new MenuItem(); //
and a close option!
015

4 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

016 public Notepad() {


017 this.setSize(500, 300); // set the
initial size of the window
018 this.setTitle("Java Notepad Tutorial");
// set the title of the window
019 setDefaultCloseOperation(EXIT_ON_CLOSE);
// set the default close operation (exit when it
gets closed)
020 this.textArea.setFont(new Font("Century
Gothic", Font.BOLD, 12)); // set a default font
for the TextArea
021 // this is why we didn't have to worry
about the size of the TextArea!
022 this.getContentPane().setLayout(new
BorderLayout()); // the BorderLayout bit makes
it fill it automatically
023 this.getContentPane().add(textArea);
024
025 // add our menu bar into the GUI
026 this.setMenuBar(this.menuBar);
027 this.menuBar.add(this.file); // we'll
configure this later
028
029 // first off, the design of the menuBar
itself. Pretty simple, all we need to do
030 // is add a couple of menus, which will
be populated later on
031 this.file.setLabel("File");
032
033 // now it's time to work with the menu.
I'm only going to add a basic File menu
034 // but you could add more!
035
036 // now we can start working on the
content of the menu~ this gets a little
repetitive,
037 // so please bare with me!
038
039 // time for the repetitive stuff. let's
add the "Open" option
040 this.openFile.setLabel("Open"); // set
the label of the menu item
041 this.openFile.addActionListener(this);
// add an action listener (so we know when it's
been clicked
042 this.openFile.setShortcut(new
MenuShortcut(KeyEvent.VK_O, false)); // set a
keyboard shortcut
043 this.file.add(this.openFile); // add it
to the "File" menu
044
045 // and the save...
046 this.saveFile.setLabel("Save");
047 this.saveFile.addActionListener(this);
048 this.saveFile.setShortcut(new
MenuShortcut(KeyEvent.VK_S, false));
049 this.file.add(this.saveFile);
050
051 // and finally, the close option
052 this.close.setLabel("Close");
053 // along with our "CTRL+F4" shortcut to
close the window, we also have
054 // the default closer, as stated at the

5 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

beginning of this tutorial.


055 // this means that we actually have TWO
shortcuts to close:
056 // 1) the default close operation
(example, Alt+F4 on Windows)
057 // 2) CTRL+F4, which we are about to
define now: (this one will appear in the label)
058 this.close.setShortcut(new
MenuShortcut(KeyEvent.VK_F4, false));
059 this.close.addActionListener(this);
060 this.file.add(this.close);
061 }
062
063 public void actionPerformed (ActionEvent e)
{
064 // if the source of the event was our
"close" option
065 if (e.getSource() == this.close)
066 this.dispose(); // dispose all
resources and close the application
067
068 // if the source was the "open" option
069 else if (e.getSource() == this.openFile)
{
070 JFileChooser open = new
JFileChooser(); // open up a file chooser (a
dialog for the user to browse files to open)
071 int option =
open.showOpenDialog(this); // get the option
that the user selected (approve or cancel)
072 // NOTE: because we are OPENing a
file, we call showOpenDialog~
073 // if the user clicked OK, we have
"APPROVE_OPTION"
074 // so we want to open the file
075 if (option ==
JFileChooser.APPROVE_OPTION) {
076 this.textArea.setText(""); //
clear the TextArea before applying the file
contents
077 try {
078 // create a scanner to read
the file (getSelectedFile().getPath() will get
the path to the file)
079 Scanner scan = new
Scanner(new
FileReader(open.getSelectedFile().getPath()));
080 while (scan.hasNext()) //
while there's still something to read
081 this.textArea.append(scan.nextLine()
+ "\n"); // append the line to the TextArea
082 } catch (Exception ex) { //
catch any exceptions, and...
083 // ...write to the debug
console
084 System.out.println(ex.getMessage());
085 }
086 }
087 }
088
089 // and lastly, if the source of the
event was the "save" option
090 else if (e.getSource() == this.saveFile)

6 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

{
091 JFileChooser save = new
JFileChooser(); // again, open a file chooser
092 int option =
save.showSaveDialog(this); // similar to the
open file, only this time we call
093 // showSaveDialog instead of
showOpenDialog
094 // if the user clicked OK (and not
cancel)
095 if (option ==
JFileChooser.APPROVE_OPTION) {
096 try {
097 // create a buffered writer
to write to a file
098 BufferedWriter out = new
BufferedWriter(new
FileWriter(save.getSelectedFile().getPath()));
099 out.write(this.textArea.getText());
// write the contents of the TextArea to the file
100 out.close(); // close the
file stream
101 } catch (Exception ex) { //
again, catch any exceptions and...
102 // ...write to the debug
console
103 System.out.println(ex.getMessage());
104 }
105 }
106 }
107 }
108 // the main method, for actually creating
our notepad and setting it to visible.

Happy coding!
Attached image(s)
Resized to 79% (was 640 x 373) - Click image to enlarge

Replies To: Creating a basic Notepad Application

Locke
Posted 05 October 2008 - 08:55 AM
Nice tutorial! :^:
ran123

7 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

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.
skywalkno8
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!!
gabehabe
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! :)

1 public static void main(String args[]) {


2 Notepad app = new Notepad();
3 app.setVisible(true);
4 }

skywalkno8
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..
Ostralis
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!
sama_thebest
Posted 16 December 2008 - 10:18 PM
very very nice :^: :^: :^: :^:
5thWall
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.
bastones
Posted 13 January 2009 - 05:07 PM

(http://www.dreamincode.net/forums
/index.php?s=d55461f6076a23df73631e5feeab5889&app=forums&
module=forums&section=findpost&pid=493829) 5thWall, 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:

1 private MenuBar menuBar = new MenuBar(); //


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

8 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

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.
5thWall
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:

01 private int A;
02 private int B;
03
04 //We use the name A twice so we use 'this' to
tell them apart.
05 public setA(int A) {
06 this.A = A;
07 }
08
09 //The name B is only used once so we don't need
'this' here.
10 public setB(int _B)/> {
11 B = _B;
12 }

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
bastones
Posted 14 January 2009 - 11:21 AM

(http://www.dreamincode.net/forums
/index.php?s=d55461f6076a23df73631e5feeab5889&app=forums&
module=forums&section=findpost&pid=511477) 5thWall, 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:

01 private int A;
02 private int B;
03
04 //We use the name A twice so we use 'this' to
tell them apart.
05 public setA(int A) {
06 this.A = A;
07 }
08
09 //The name B is only used once so we don't need
'this' here.
10 public setB(int _B)/> {
11 B = _B;
12 }

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
(http://java.sun.com/docs/books/tutorial/java/javaOO
/thiskey.html) for a quick overview of the keyword because
there are a few more uses for it.
gabehabe
Posted 18 January 2009 - 09:34 AM
Sorry about the late response~!

9 of 10 3/9/2017 4:11 AM
Creating A Basic Notepad Application - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/66176-creating-a-basic-notepa...

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
(http://www.dreamincode.net/code/snippet2571.htm)

Enjoy~! :)
joezim007
Posted 23 January 2009 - 09:46 AM

(http://www.dreamincode.net/forums
/index.php?s=d55461f6076a23df73631e5feeab5889&app=forums&
module=forums&section=findpost&pid=511389) bastones, on 13
Jan, 2009 - 05:07 PM, said:
(http://www.dreamincode.net/forums
/index.php?s=d55461f6076a23df73631e5feeab5889&app=forums&
module=forums&section=findpost&pid=493829) 5thWall, 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:

1 private MenuBar menuBar = new MenuBar(); //


first, create a MenuBar item
2 private Menu file = new Menu(); // our File
menu
3 // what's going in File? let's see...
4 private MenuItem openFile = new MenuItem();
// an open option
5 private MenuItem saveFile = new MenuItem();
// a save option
6 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.
joezim007
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?
(4 Pages)

1
2
3

QueryLast unknown local index
failed:
'forums_search_posts_main' in search request.

10 of 10 3/9/2017 4:11 AM

You might also like