Simple Text Editor with Java Swing
Programming March 19th, 2008Hi again, for this post I decided to demonstrate JAVA’s Swing library.With this library it is easy to create applications with GUI.Anyway I never prefer to write Windows applications in JAVA, however if you need cross-platform stuff, Swing may be a choice.Unlike awt, Swing looks like same in the all platforms. This simple Editor program, uses JMenuBar (Standard Menubar) , JToolBar (Standard Toolbar) , JDesktop (MDI) , Images for buttons , also Editor is capable of inserting images to the text. (StyledDocument).
Here is the source code:
//Simple Editor / Styled Document Editor
//coded by Burak Ozdemir
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.rtf.RTFEditorKit;
public class Editor extends JFrame {
ArrayList
ArrayList
JDesktopPane desktop;
// Some required variables to make multiple file handling easy
File selectedfile;
Editor() {
// Initializing variables and creating gui
Editors = new ArrayList
Frames = new ArrayList
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Mdi documenting
desktop = new JDesktopPane();
// Create Menu
JMenuBar menuBar = drawMenu();
frame.setJMenuBar(menuBar);
// Create Toolbar
JToolBar toolBar = drawToolBar();
frame.add(toolBar, BorderLayout.PAGE_START);
// Some styling
frame.add(desktop, BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setTitle(”Simple Text Editor”);
}
public static void main(String[] args) {
// Running main program
new Editor();
}
// this function is used to save documents
private void saveDocument() {
try {
// Determine the currently active pane
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
// Save file
File myFile = new File(ifrm.getTitle());
System.out.println(ifrm.getTitle());
FileOutputStream fo = new FileOutputStream(myFile);
ObjectOutputStream oos = new ObjectOutputStream(fo);
oos.writeObject(jedp.getStyledDocument());
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
System.out.println(”File not found”);
} catch (IOException e) {
System.out.println(”I/O error”);
}
}
// this function is used to load documents
private void loadDocument() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(”Open an existing file”);
int result = fileChooser.showOpenDialog(Editor.this);
if (result == JFileChooser.APPROVE_OPTION) {
selectedfile = fileChooser.getSelectedFile();
try {
JInternalFrame internalFrame = new JInternalFrame(selectedfile.getCanonicalPath(), true, true, true,
true);
desktop.add(internalFrame);
internalFrame.setBounds(desktop.getAllFrames().length * 20 + 5, desktop.getAllFrames().length * 20 + 5,
640, 480);
internalFrame.setVisible(true);
RTFEditorKit rtfEditor = new RTFEditorKit();
JTextPane _resultArea = new JTextPane();
// _resultArea.setText(”Enter more text to see scrollbars”);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
// JScrollPane scrollingArea = new JScrollPane(rtfEditor);
_resultArea.setEditorKit(rtfEditor);
internalFrame.add(scrollingArea);
FileInputStream fi = new FileInputStream(selectedfile);
ObjectInputStream ois = new ObjectInputStream(fi);
_resultArea.setStyledDocument((StyledDocument) ois.readObject());
validate();
ois.close();
Editors.add(_resultArea);
Frames.add(internalFrame);
fi.close();
} catch (FileNotFoundException e) {
System.out.println(”File not found”);
} catch (IOException e) {
System.out.println(”I/O error”);
} catch (Exception e) {
e.printStackTrace();
}
}
} // this function is used to create new/empty document
private void newDocument() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(”Create a new file”);
int result = fileChooser.showOpenDialog(Editor.this);
if (result == JFileChooser.APPROVE_OPTION) {
selectedfile = fileChooser.getSelectedFile();
try {
selectedfile.createNewFile();
} catch (IOException e) {
System.out.println(”I/O error”);
}
try {
JInternalFrame internalFrame = new JInternalFrame(selectedfile.getCanonicalPath(), true, true, true,
true);
desktop.add(internalFrame);
internalFrame.setBounds(desktop.getAllFrames().length * 20 + 5, desktop.getAllFrames().length * 20 + 5,
640, 480);
internalFrame.setVisible(true);
RTFEditorKit rtfEditor = new RTFEditorKit();
JTextPane _resultArea = new JTextPane();
// _resultArea.setText(”Enter more text to see scrollbars”);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
// JScrollPane scrollingArea = new JScrollPane(rtfEditor);
_resultArea.setEditorKit(rtfEditor);
internalFrame.add(scrollingArea);
FileInputStream fi = new FileInputStream(selectedfile);
rtfEditor.read(fi, _resultArea.getDocument(), 0);
Editors.add(_resultArea);
Frames.add(internalFrame);
fi.close();
} catch (FileNotFoundException e) {
System.out.println(”File not found”);
} catch (IOException e) {
System.out.println(”I/O error”);
} catch (BadLocationException e) {}
}
}
// Create our toolbar
private JToolBar drawToolBar() {
JToolBar myBar = new JToolBar(”Tool Bar”);
// Our buttons
JButton new_button = new JButton(”New”);
new_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
newDocument();
}
});
myBar.add(new_button);
JButton open_button = new JButton(”Open”);
open_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadDocument();
}
});
myBar.add(open_button);
JButton save_button = new JButton(”Save”);
save_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
saveDocument();
}
});
myBar.add(save_button);
JButton copy_button = new JButton(”Copy”);
copy_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.copy();
}
});
myBar.add(copy_button);
JButton paste_button = new JButton(”Paste”);
paste_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.paste();
}
});
myBar.add(paste_button);
JButton fontitalic_button = new JButton(”Italic”);
fontitalic_button.addActionListener(new StyledEditorKit.ItalicAction());
myBar.add(fontitalic_button);
JButton fontbold_button = new JButton(”Bold”);
fontbold_button.addActionListener(new StyledEditorKit.BoldAction());
myBar.add(fontbold_button);
JButton color_button = new JButton(”Color”);
color_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(Editor.this, “Color Chooser”, Color.cyan);
if (color != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, color);
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.setCharacterAttributes(attr, false);
}
}
});
myBar.add(color_button);
return myBar;
}
// Our menu bar
private JMenuBar drawMenu() {
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu file = new JMenu(”File”);
JMenu edit = new JMenu(”Edit”);
JMenu insert = new JMenu(”Insert”);
JMenu format = new JMenu(”Format”);
JMenu view = new JMenu(”View”);
JMenu fontsize = new JMenu(”Size”);
JMenu fontface = new JMenu(”Font Face”);
JMenu fontstyle = new JMenu(”Font Style”);
menuBar.add(file);
menuBar.add(edit);
menuBar.add(insert);
menuBar.add(format);
menuBar.add(view);
JMenuItem _new = new JMenuItem(”New…”);
_new.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
newDocument();
}
});
JMenuItem _open = new JMenuItem(”Open…”);
_open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadDocument();
}
});
JMenuItem _save = new JMenuItem(”Save…”);
_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
saveDocument();
}
});
JMenuItem _exit = new JMenuItem(”Exit”);
_exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(_new);
file.add(_open);
file.add(_save);
file.add(_exit);
JMenuItem _copy = new JMenuItem(”Copy”);
_copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.copy();
}
});
JMenuItem _paste = new JMenuItem(”Paste”);
_paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.paste();
}
});
edit.add(_copy);
edit.add(_paste);
JMenuItem _picture = new JMenuItem(”Picture”);
_picture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(”Select an image file”);
int result = fileChooser.showOpenDialog(Editor.this);
if (result == JFileChooser.APPROVE_OPTION) {
selectedfile = fileChooser.getSelectedFile();
ImageIcon _img = new ImageIcon(selectedfile.getAbsolutePath());
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.insertIcon(_img);
}
}
});
insert.add(_picture);
// Font Sizes
JMenuItem _size_12 = new JMenuItem(”12″);
_size_12.addActionListener(new StyledEditorKit.FontSizeAction(”font-size-12″, 12));
JMenuItem _size_14 = new JMenuItem(”14″);
_size_14.addActionListener(new StyledEditorKit.FontSizeAction(”font-size-14″, 14));
fontsize.add(_size_12);
fontsize.add(_size_14);
format.add(fontsize);
// Font Families
JMenuItem _sans = new JMenuItem(”SansSerif”);
_sans.addActionListener(new StyledEditorKit.FontFamilyAction(”font-family-Serif”, “Serif”));
JMenuItem _mono = new JMenuItem(”Monospaced”);
_mono.addActionListener(new StyledEditorKit.FontFamilyAction(”font-family-Monospaced”, “Monospaced”));
fontface.add(_sans);
fontface.add(_mono);
format.add(new JSeparator());
format.add(fontface);
// Font Styles
JMenuItem _bold = new JMenuItem(”Bold”);
_bold.addActionListener(new StyledEditorKit.BoldAction());
JMenuItem _italic = new JMenuItem(”Italic”);
_italic.addActionListener(new StyledEditorKit.ItalicAction());
JMenuItem _underlined = new JMenuItem(”Underlined”);
_underlined.addActionListener(new StyledEditorKit.UnderlineAction());
fontstyle.add(_bold);
fontstyle.add(_italic);
fontstyle.add(_underlined);
format.add(new JSeparator());
format.add(fontstyle);
// Font Color
JMenuItem _color = new JMenuItem(”Color”);
_color.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(Editor.this, “Color Chooser”, Color.cyan);
if (color != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, color);
JInternalFrame ifrm = desktop.getSelectedFrame();
int _index = -1;
for (int i = 0; i < Frames.size(); ++i) {
if (Frames.get(i) == ifrm) {
_index = i;
}
}
JTextPane jedp = Editors.get(_index);
jedp.setCharacterAttributes(attr, false);
}
}
});
format.add(new JSeparator());
format.add(_color);
// Change window style to Motif
JMenuItem _windows = new JMenuItem(”Windows”);
_windows.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(”com.sun.java.swing.plaf.motif.MotifLookAndFeel”);
} catch (Exception ex) {
System.out.println(”Error changing style to Motif: ” + ex);
}
}
});
view.add(_windows);
return menuBar;
}
}
Technorati Tags: Java, Swing, Editor, Programming, JMenuBar, JToolBar, JDesktop
Some other posts that you may like :
Back to the work after a long breakMultiple Find & Replace
Golden Rule 'Content'
Win32 API Introduction
LG Makes It Thin
NVIDIA Demo: Human Head Video
First Order Logic Parser (Soon)
HP Pavilion HDX Gaming Notebook
Threading in C#
A* Search Algorithm / C# Implementation

























































March 28th, 2008 at 2:25 pm
[…] Here is the source code: (more…) […]
May 31st, 2008 at 11:51 pm
Hi Burak!
I am a beginner in Java language. I want to thank to you for the Simple Text Editor program, because it helped me to understand how works the saving and opening a styled ducument in Java.
I wish you many succeses in your work!
Thanks! Kind regards: Pelz.
June 1st, 2008 at 2:43 am
I’m happy to hear that, Soon I’ll add some other examples, they may help too.
Take care Pelz.
Burak.
August 30th, 2008 at 7:47 am
I need to develop a RTF Text Editor which should support text attributes like (Bold, Italic, Underline, TextColor, FontName, FontSize, Alignments like LEFT,RIGHT,CENTER,JUSTIFY and Bullet Styles).
With the above code I can able to get except Alignments and Bullet styles.
Can you please update those two styles related code.
Its urgent. I tried a lot, but could not able to get a perfect solution.
Looking forward your kind cooperation.
Thanks in Advance.