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:
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?
1 |
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.
1 |
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 0×0 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:
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! |
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:
02 |
this.setSize(500, 300); // set the initial size of the window |
03 |
this.setTitle("Java Notepad Tutorial"); // set the title of the window |
04 |
setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed) |
05 |
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea |
06 |
// this is why we didn't have to worry about the size of the TextArea! |
07 |
this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically |
08 |
this.getContentPane().add(textArea); |
10 |
// add our menu bar into the GUI |
11 |
this.setMenuBar(this.menuBar); |
12 |
this.menuBar.add(this.file); // we'll configure this later |
14 |
// first off, the design of the menuBar itself. Pretty simple, all we need to do |
15 |
// is add a couple of menus, which will be populated later on |
16 |
this.file.setLabel("File"); |
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! |
21 |
// now we can start working on the content of the menu~ this gets a little repetitive, |
22 |
// so please bare with me! |
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 MenuShortcut(KeyEvent.VK_O, false)); // set a keyboard shortcut |
28 |
this.file.add(this.openFile); // add it to the "File" menu |
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); |
36 |
// and finally, the close option |
37 |
this.close.setLabel("Close"); |
38 |
// along with our "CTRL+F4" shortcut to close the window, we also have |
39 |
// the default closer, as stated at the beginning of this tutorial. |
40 |
// this means that we actually have TWO shortcuts to close: |
41 |
// 1) the default close operation (example, Alt+F4 on Windows) |
42 |
// 2) CTRL+F4, which we are about to define now: (this one will appear in the label) |
43 |
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false)); |
44 |
this.close.addActionListener(this); |
45 |
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
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 |
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" |
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 |
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()); |
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 |
32 |
// if the user clicked OK (and not cancel) |
33 |
if (option == JFileChooser.APPROVE_OPTION) { |
35 |
// create a buffered writer to write to a file |
36 |
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath())); |
37 |
out.write(this.textArea.getText()); // write the contents of the TextArea to the file |
38 |
out.close(); // close the file stream |
39 |
} catch (Exception ex) { // again, catch any exceptions and... |
40 |
// ...write to the debug console |
41 |
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!
001 |
import javax.swing.*; |
003 |
import java.awt.event.*; |
004 |
import java.util.Scanner; |
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! |
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); |
025 |
// add our menu bar into the GUI |
026 |
this.setMenuBar(this.menuBar); |
027 |
this.menuBar.add(this.file); // we'll configure this later |
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"); |
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! |
036 |
// now we can start working on the content of the menu~ this gets a little repetitive, |
037 |
// so please bare with me! |
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 |
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); |
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 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); |
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 |
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 |
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()); |
089 |
// and lastly, if the source of the event was the "save" option |
090 |
else if (e.getSource() == this.saveFile) { |
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) { |
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()); |
108 |
// the main method, for actually creating our notepad and setting it to visible. |
109 |
public static void main(String args[]) { |
110 |
Notepad app = new Notepad(); |
111 |
app.setVisible(true); |
Happy coding!
Attached image(s)
-
Resized to 79% (was 640 x 373) – Click image to enlarge

0.000000
0.000000
I conceive this internet site has some real superb information for everyone. “A kiss, is the physical transgression of the mental connection which has already taken place.” by Tanielle Naus.
I like this blog it’s a master piece! Glad I noticed this on google.
There is visibly a bunch to know about this. I assume you made some nice points in features also.
Regards for all your efforts that you have put in this. Very interesting info. “Friends do not live in harmony merely, as some say, but in melody.” by Henry David Thoreau.
I am glad to be a visitant of this double dyed blog, regards for this rare info!Unquestionably consider that which you stated. Your favorite justification seemed to be on the net the easiest factor to take note of. I say to you, I certainly get annoyed even as other people think about issues that they plainly do not recognize about. You managed to hit the nail upon the top as well as outlined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thank you!
I view something truly interesting about your web site so I saved to bookmarks .
The root of your writing while appearing reasonable at first, did not settle properly with me after some time. Somewhere within the paragraphs you managed to make me a believer but just for a short while. I however have a problem with your leaps in assumptions and one might do nicely to help fill in all those gaps. In the event you actually can accomplish that, I will definitely end up being amazed.
Just a smiling visitant here to share the enjoy (:, btw outstanding style .
Excellent read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch because I found it for him smile Thus let me rephrase that: Thanks for lunch! “We know what happens to people who stay in the middle of the road. They get run over.” by Ambrose Gwinett Bierce.
Hello admin good post very much thanks beloved this blog really very much
Very interesting details you have observed , regards for posting . “The thing always happens that you really believe in and the belief in a thing makes it happen.” by Frank Lloyd Wright.
Hey there! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading through your articles. Can you recommend any other blogs/websites/forums that deal with the same topics? Appreciate it!
You have brought up a very wonderful details , regards for the post. “I am not an adventurer by choice but by fate.” by Vincent Van Gogh.
I would learn more on this topic in case the content offered have been as interesting as what you wrote on this page. Don’t stop caring about the content you write.
Definitely consider that which you stated. Your favorite reason appeared to be on the web the simplest thing to understand of. I say to you, I definitely get irked even as other people think about concerns that they just don’t recognize about. You managed to hit the nail upon the top and also outlined out the whole thing with no need side effect , people could take a signal. Will probably be back to get more. Thank you!
Please let me know if you’re looking for a article author for your site. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!
apron Deirdre patassy leotaru aviation uproar characterless firepower nominal
I like this web blog it’s a master piece! Glad I observed this on google.
Very nice layout and fantastic written content, practically nothing else we want
.
I really like your writing style, good information, thank you for putting up
. “In university they don’t tell you that the greater part of the law is learning to tolerate fools.” by Doris Lessing.
I like this website so much, saved to favorites. “To hold a pen is to be at war.” by Francois Marie Arouet Voltaire.
Utterly composed articles , thanks for selective information .
You have brought up a very superb details , appreciate it for the post. “There’s two heads to every coin.” by Jerry Coleman.
There a link to my blogpost as a related article. I have migrated my blog from the old virendrachandak.wordpress.com to techtalk.virendrachandak.com. I have added redirection on the old domain to redirect to the new domain. I request you to please update the link to point to my new domain.
Old link:http://virendrachandak.wordpress.com/2011/12/10/notepad-keyboard-shortcuts/
Notepad++ Keyboard Shortcuts (virendrachandak.wordpress.com)
New Link: http://techtalk.virendrachandak.com/notepad-keyboard-shortcuts/