Beginner text editor

I wrote a simple text editor and I would like to get some critical comments. Below I present only a main part of code. I removed icons, irrelevant functions, etc. I am aware,that JTextArea is not best choice for text editor, however I purposely didn't choose JTextPane because at my level it seems too complicated.

I would be very grateful for a comments on:

• code structure - is it a good idea, to put everything in the one class, or it would be better to divide it between couple of classes?
• division of tasks between classes - is it good solution to use multiple methods to create different parts of a GUI?
• events handling - is it good practice to cumulate Action Listeners of multiple objects under one class? or is it better and more transparent to create one class per action or per group of related actions?
• fields - is there too many of them? what is a good alternative for them? getter method?

Any other advice will be appreciated.



import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.Object;

public class SimpleTextEditor{
private JFrame frame;
private Action newAction,openAction,saveAction,saveAsAction,boldAction,italicsAction,copyAction,cutAction,pasteAction,printAction,findAction;
private JTextArea mainTextArea;
private JTextField findField,replaceField;
private JFileChooser fileChooser;
private File file;
private int boldCheck,italicsCheck,caseCheck,replaceCheck,keepSearch;
private JComboBox<String>fontTypeList,fontSizeList;
private JButton findNext,replace,findAll,replaceAll,okFind,find,previousFind;
private JDialog findDialog;
private JCheckBox caseSensitive;
private Highlighter highlighter;

public static void main(String[]args){
SimpleTextEditor simpleNote=new SimpleTextEditor();
simpleNote.go();
}

private void go(){
frame=new JFrame();
JPanel background = new JPanel();
frame.setTitle("New Document"+"-SimpleTextEditor v.2");
frame.setLocationByPlatform(true);
background.setLayout(new BorderLayout());
createActions();

findDialog=getFindAndReplace();

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);

}

newFile.setIcon(null);
openFile.setIcon(null);
saveFile.setIcon(null);
saveAsFile.setIcon(null);
print.setIcon(null);

}

private JScrollPane getTextArea(){
mainTextArea=new JTextArea();
highlighter = mainTextArea.getHighlighter();
Font mainFont=new Font("Ariala",Font.PLAIN,12);

mainTextArea.setFont(mainFont);
mainTextArea.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
mainTextArea.setLineWrap(true);
mainTextArea.setWrapStyleWord(true);

JScrollPane textScroll=new JScrollPane(mainTextArea);
textScroll
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textScroll
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

return textScroll;
}

private JToolBar getToolBar(){
boldCheck=0;
italicsCheck=0;
JToolBar toolBar=new JToolBar();
AbstractButton newTool=new JButton(newAction);
AbstractButton openTool=new JButton(openAction);
AbstractButton saveTool=new JButton(saveAction);
AbstractButton printTool=new JButton(printAction);
AbstractButton bold=new JButton(boldAction);
AbstractButton italics=new JButton(italicsAction);
toolBar.setFloatable(false);

}

private JComboBox<String>getFontsList(){
String fonts[]=GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
fontTypeList=new JComboBox<String>(fonts);
fontTypeList.setSelectedIndex(6);
fontTypeList.setPreferredSize(new Dimension(280,28));
fontTypeList.setMaximumSize(new Dimension(280,28));
return fontTypeList;
}

private JComboBox<String>getFontSizeList(){
String[]size=new String[95];
for(int i=0;i<95;i++){
size[i]=String.valueOf(i+6);
}
fontSizeList=new JComboBox<String>(size);
fontSizeList.setSelectedIndex(6);
fontSizeList.setPreferredSize(new Dimension(49,28));
fontSizeList.setMaximumSize(new Dimension(49,28));

return fontSizeList;
}

public JDialog getFindAndReplace(){
JDialog findAndReplaceWin=new JDialog(frame,"Find and replace");
JPanel findAndReplacePanel=new JPanel();
findAndReplacePanel.setLayout(new GridLayout(7,1,2,2));
JPanel findPanel1=new JPanel(new GridLayout(1,2));
JPanel findPanel2=new JPanel(new GridLayout(1,2));
JPanel replacePanel=new JPanel(new GridLayout(1,2));

keepSearch=0;
findField=new JTextField("find");
replaceField=new JTextField("replace");
find=new JButton("Find");
findNext=new JButton("Next");
previousFind=new JButton("Previous");
findAll=new JButton("Find all");
replace=new JButton("Replace");
replaceAll=new JButton("Replace all");
caseSensitive=new JCheckBox("Case sensitive");
caseSensitive.setSelected(true);
okFind=new JButton("OK");
findAndReplaceWin.pack();
findAndReplaceWin.setLocationRelativeTo(frame);
findAndReplaceWin.setVisible(false);
findAndReplaceWin.setEnabled(false);
return findAndReplaceWin;
}

private void createActions(){

newAction=new MainActions("New",null,"Create new file",
saveAction=new MainActions("Save",null,
"Save file in existing file",KeyStroke.getKeyStroke(
openAction=new MainActions("Open",null,"Open file",
saveAsAction=new MainActions("Save as",null,
"Save in selected file",KeyStroke.getKeyStroke(KeyEvent.VK_A,
boldAction=new MainActions("Bold",null,"Bold font",
italicsAction=new MainActions("Italics",null,"Italic font",
printAction=new MainActions("Print",null,"Print the file",
copyAction=new MainActions("Copy",null,"Copy the selected text",
cutAction=new MainActions("Cut",null,"Copy the selected text",
pasteAction=new MainActions("Paste",null,"Copy the selected text",
findAction=new MainActions("Find and replace",null,
"Search for and replace input word",KeyStroke.getKeyStroke(
}

private void save(){
try{
file=fileChooser.getSelectedFile();
BufferedWriter writer=new BufferedWriter(new FileWriter(file));
mainTextArea.write(writer);
writer.close();
frame.setTitle(file.getName()+"-SimpleTextEditor v.2");
}catch(IOException ioException){
ioException.printStackTrace();
}
}

public void find(){
String text;
int endPoint;
int findPoint;

text=mainTextArea.getText();

String searchString=findField.getText();
if(caseCheck==1){
text=text.toLowerCase();
searchString=searchString.toLowerCase();
}

Highlighter.HighlightPainter painter=new DefaultHighlighter.DefaultHighlightPainter(
Color.LIGHT_GRAY);

findPoint=text.indexOf(searchString,keepSearch);
endPoint=findPoint+searchString.length();
if(findPoint!=-1){
try{
ex.printStackTrace();
}
keepSearch=endPoint;
}else{
JOptionPane.showMessageDialog(findDialog,
"Warning!",JOptionPane.WARNING_MESSAGE);
}
}

public void replace(){
String text=mainTextArea.getText();
String findString=findField.getText();
String replaceString=replaceField.getText();
text=text.substring(0,keepSearch-findString.length())
+replaceString+text.substring(keepSearch);
mainTextArea.setText(text);

}

private class MainActions extends AbstractAction{
public MainActions(String name,ImageIcon icon,String desc,KeyStroke key){
super(name,icon);
putValue(SHORT_DESCRIPTION,desc);
putValue(ACCELERATOR_KEY,key);
}

public void actionPerformed(ActionEvent event){
Object source=event.getActionCommand();
if(source.equals("New")){
System.out.println(event.getActionCommand());
mainTextArea.setText("");
file=null;
frame.setTitle("New Document"+"-SimpleTextEditor v.2");
}else if(source.equals("Save")){
if(file==null){
fileChooser=new JFileChooser();
fileChooser.showSaveDialog(frame);
save();
}else{
save();
}
}else if(source.equals("Save as")){
fileChooser=new JFileChooser();
fileChooser.showSaveDialog(frame);
save();
}else if(source.equals("Open")){
try{
mainTextArea.setText("");
fileChooser=new JFileChooser();
fileChooser.showOpenDialog(frame);
file=fileChooser.getSelectedFile();
InputStream inputStream=new FileInputStream(file);
inputStream,"UTF-8");
frame.setTitle(file.getName()+"-SimpleTextEditor v.2");
}catch(IOException ioException){
ioException.printStackTrace();
}
}else if(source.equals("Bold")){
if(boldCheck==0){
mainTextArea.setFont(new Font(mainTextArea.getFont()
.getName(),Font.BOLD,mainTextArea.getFont()
.getSize()));
boldCheck=1;
italicsCheck=0;
}else if(boldCheck==1){
mainTextArea.setFont(new Font(mainTextArea.getFont()
.getName(),Font.PLAIN,mainTextArea.getFont()
.getSize()));
boldCheck=0;
italicsCheck=0;
}
}else if(source.equals("Italics")){
if(italicsCheck==0){
mainTextArea.setFont(new Font(mainTextArea.getFont()
.getName(),Font.ITALIC,mainTextArea.getFont()
.getSize()));
italicsCheck=1;
boldCheck=0;
}else if(italicsCheck==1){
mainTextArea.setFont(new Font(mainTextArea.getFont()
.getName(),Font.PLAIN,mainTextArea.getFont()
.getSize()));
italicsCheck=0;
boldCheck=0;
}
}else if(source.equals("Print")){
try{
mainTextArea.print(null,null,true,null,null,true);
}catch(Exception ex){
ex.printStackTrace();
}
}else if(source.equals("Copy")){
mainTextArea.copy();
}else if(source.equals("Cut")){
mainTextArea.cut();
}else if(source.equals("Paste")){
mainTextArea.paste();
}else if(source.equals("Find and replace")){
if(mainTextArea.getSelectedText()!=null){
findField.setText(mainTextArea.getSelectedText());
}
findDialog.setVisible(true);
findDialog.setEnabled(true);
}
}
}

private class ComboBoxListener implements ActionListener{
public void actionPerformed(ActionEvent event){
Object source=event.getSource();
if(source==fontTypeList){
mainTextArea.setFont(new Font(fontTypeList.getSelectedItem()
.toString(),mainTextArea.getFont().getStyle(),
mainTextArea.getFont().getSize()));

}else if(source==fontSizeList){
mainTextArea.setFont(new Font(mainTextArea.getFont().getName(),
mainTextArea.getFont().getStyle(),Integer
.parseInt(fontSizeList.getSelectedItem()
.toString())));

}
}
}

public void mouseReleased(MouseEvent e){
}

if(e.isPopupTrigger()){
}
}
}

private class exitListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}

private class FARListener implements ActionListener{
public void actionPerformed(ActionEvent e){
Object source=e.getSource();
if(source==find){
highlighter.removeAllHighlights();
keepSearch=0;
replaceCheck=1;
find();
}else if(source==findNext){
highlighter.removeAllHighlights();
find();
}else if(source==previousFind){
highlighter.removeAllHighlights();
System.out.println(keepSearch);
keepSearch=mainTextArea.getText().lastIndexOf(
findField.getText(),
keepSearch-findField.getText().length()-1);
System.out.println(keepSearch);
find();
}else if(source==findAll){
do{
find();
}while(keepSearch<mainTextArea.getText().lastIndexOf(
findField.getText()));
}else if(source==replace){
if(replaceCheck!=0){
replace();
}
replaceCheck=0;
}else if(source==replaceAll){
keepSearch=0;
do{
find();
replace();
}while(mainTextArea.getText().contains(findField.getText()));
}else if(source==caseSensitive){
if(caseSensitive.isSelected()){
caseCheck=0;
}else{
caseCheck=1;
}
}else if(source==okFind){
findDialog.setVisible(false);
findField.setText("find");
replaceField.setText("replace");
mainTextArea.setCaretPosition(mainTextArea.getText().length());
}
}
}
}


• First thing I can say, thanks to not have extends JFrame! And I understand your feelings about too many field, but with Swing I did not see another good alternative (I did not design that much UI with it) – Marc-Andre Mar 24 '15 at 15:18

You are asking all the right questions :)

code structure - is it a good idea, to put everything in the one class, or it would be better to divide it between couple of classes?

No, putting everything in one giant class is not a good idea at all. It makes it impossible to reuse part of the code in other projects, it makes it really hard to find the code you are interested in, and it will also make it very hard to add new functionality later on (because you can't just concentrate on the relevant classes; you only have one class, so everything is relevant all the time).

A class should ideally only be responsible for one thing. So you might have a model class, which holds the entered text, and offers methods to manipulate it (such as search something in it, replace, etc). Saving/Loading should also happen in a separate class. And you could separate some gui elements into their own class as well (such as main menu, toolbar, search-and-replace window, etc).

You should also definitely split up your actions class. Give each action it's own class. And never use strings like this for program flow (if you must use your approach, use enums).

division of tasks between classes - is it good solution to use multiple methods to create different parts of a GUI?

Yes, definitely. Methods should - just like classes - really only be responsible for one thing. Ideally, this makes them reusable, and it definitely makes your code easier to read.

events handling - is it good practice to cumulate Action Listeners of multiple objects under one class? or is it better and more transparent to create one class per action or per group of related actions

No, such an accumulation is not very good, as it's really hard to read and maintain.

fields - is there too many of them? what is a good alternative for them? getter method?

Yes, you have way too many fields, which makes your code quite hard to read. If you split your code up into multiple classes, you should already see a reduction in fields. Then, you might also notice that some fields don't actually need to be fields, but could be declared at method levels.

Misc

• use more spaces to increase readability (eg around =, ==, etc).
• don't declare multiple fields in one line, it makes it easy to overlook a field (and it makes it easy to not realize that way too many fields were added :) ).
• don't just print the stacktrace of exceptions, but handle them (maybe your users write something important). For example, if you couldn't save, display a popup box notifying the user of this (and give them the opportunity to copy their work).
• Thank you very much for answer! However i have some question to answer about "code structure". So would it be ok to have for example 20 separate classes in project like mine text editor? Is it useful in projects of any scale? And generally, is possible to have too many classes? – m.cekiera Mar 25 '15 at 13:40
• @m.cekiera I mean, I can theoretically imagine having too many classes, but I think that you would notice that (because they would not do anything, but eg only wrap other classes). In practice, I don't think I ever thought that a project had too many classes, so that is not something I would worry about. And yes, for any project that is not a throw-away one-time test, it is useful to separate code into different classes, no matter the size of the project (I guess there can be projects that are so tiny that there is no need for multiple classes, but yours would definitely not be one of them). – tim Mar 25 '15 at 13:58