Zamein’s Notepad – Source Code

Buongiorno a tutti,

di seguito, sperando che possa essere utile a qualcuno, trovate il codice sorgente dell’applicativo.
Il codice è, onestamente parlando, un po’ disordinato, ma è stato scritto quasi interamente di notte, dopo aver passto l’intera giornata al lavoro. Spero comunque che possa essere d’ispirazione per qualcuno.
Se avete domande non esitate a chiedere, ma potrei metterci un po’ a rispondere! (in caso non offendetevi 😉 )

L’articolo originale lo trovate qui
E’ possibile scaricare tutti i file (.java) da questo link


/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/
package menu;

import javax.swing.*;

import java.awt.event.*;

public class FileMenu extends JMenu{

private JMenuItem open, save, saveAs, exit;

public FileMenu(String name, ActionListener listener) {
super(name);
addElement(open, "Open", "ctrl O", "open", listener);
addElement(save, "Save", "ctrl S", "save", listener);
addElement(saveAs, "Save As", "ctrl D", "saveas", listener);
addElement(exit, "Exit", "ctrl E", "exit", listener);
}

private void addElement(JMenuItem item, String name, String keystroke, String actionCommand, ActionListener listener) {

item = new JMenuItem(name);
item.setAccelerator(KeyStroke.getKeyStroke(keystroke));
item.setActionCommand(actionCommand);
item.addActionListener(listener);
add(item);
}

}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/
package menu;

import javax.swing.*;
import javax.swing.text.DefaultEditorKit;

import java.awt.event.*;

public class EditMenu extends JMenu{

private JMenuItem copy, cut, paste, previous, next;

public EditMenu(String name, ActionListener listener) {
super(name);

Action copyAction = new DefaultEditorKit.CopyAction();
addElement(copy, copyAction, "Copy", "ctrl C");
Action cutAction = new DefaultEditorKit.CutAction();
addElement(cut, cutAction, "Cut", "ctrl X");
Action pasteAction = new DefaultEditorKit.PasteAction();
addElement(copy, pasteAction, "Paste", "ctrl V");

}

private void addElement(JMenuItem item, Action action, String name, String keystroke) {

item = new JMenuItem();
action.putValue(Action.NAME, name);
item.setAction(action);
item.setAccelerator(KeyStroke.getKeyStroke(keystroke));
add(item);
}
}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/
package menu;

import javax.swing.*;

import java.awt.event.*;

public class ViewMenu extends JMenu{

private JCheckBoxMenuItem fontToolBar, colorsToolBar;

public ViewMenu(String name, ActionListener listener) {
super(name);
fontToolBar = new JCheckBoxMenuItem("Font ToolBar");
fontToolBar.setActionCommand("fonttoolbar");
fontToolBar.addActionListener(listener);
fontToolBar.setSelected(true);
add(fontToolBar);

colorsToolBar = new JCheckBoxMenuItem("Colors ToolBar");
colorsToolBar.setActionCommand("colorstoolbar");
colorsToolBar.addActionListener(listener);
colorsToolBar.setSelected(true);
add(colorsToolBar);
}

public JCheckBoxMenuItem getFontToolbar() {
return fontToolBar;
}

public JCheckBoxMenuItem getColorsToolbar() {
return colorsToolBar;
}

}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/

package menu;

import javax.swing.*;

import java.awt.event.*;

public class Menu extends JMenuBar{
private FileMenu fileMenu;
private EditMenu editMenu;
private ViewMenu viewMenu;

public Menu(ActionListener listener) {
super();
fileMenu = new FileMenu("File", listener);
add(fileMenu);
editMenu = new EditMenu("Edit", listener);
add(editMenu);
viewMenu = new ViewMenu("View", listener);
add(viewMenu);
}

public ViewMenu getViewMenu() {
return viewMenu;
}

}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/
package gui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

public class ColorsToolBar extends JToolBar{

private JButton textColorButton;
private JButton backgroundColorButton;
private Color backgroundColor;
private Color textColor;
private boolean visible;

public ColorsToolBar(Color textColor, Color backgroundColor) {
super();
setLayout(new GridBagLayout());
this.textColor = textColor;
this.backgroundColor = backgroundColor;
textColorButton = new JButton("Text Color");
textColorButton.addActionListener(new TextListener());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.weightx = 100;
gbc1.weighty = 100;
gbc1.gridx = 0;
gbc1.fill = gbc1.BOTH;
gbc1.anchor = GridBagConstraints.WEST;
add(textColorButton, gbc1);
backgroundColorButton = new JButton("Background Color");
backgroundColorButton.addActionListener(new BackgroundListener());
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.weightx = 100;
gbc2.weighty = 100;
gbc2.gridx = 2;
gbc2.fill = gbc2.BOTH;
gbc2.anchor = GridBagConstraints.EAST;
add(backgroundColorButton,gbc2);
visible = true;
}

public Color getTextColor() {
return textColor;
}

public void setTextColor(Color c) {
textColor = c;
}

public Color getBackgroundColor() {
return backgroundColor;
}

public void setBackgroundColor(Color c) {
backgroundColor = c;
}
public boolean isVisible() {
return visible;
}

public void setVisible(boolean bool) {
visible = bool;
}

private class TextListener implements ActionListener {
private JDialog dialog;
private JColorChooser chooser;

public TextListener() {
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
textColor = (chooser.getColor());
}
});
dialog = new JDialog((Frame) null, false);
dialog.add(chooser);
dialog.pack();
}

public void actionPerformed(ActionEvent event) {
chooser.setColor(textColor);
dialog.setVisible(true);
}

}

private class BackgroundListener implements ActionListener {
private JDialog dialog;
private JColorChooser chooser;

public BackgroundListener() {
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
backgroundColor = chooser.getColor();
}
});
dialog = new JDialog((Frame) null, false);
dialog.add(chooser);
dialog.pack();
}

public void actionPerformed(ActionEvent event) {
chooser.setColor(backgroundColor);
dialog.setVisible(true);
}
}
}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/
package gui;

import java.awt.*;
import javax.swing.*;

public class FontToolBar extends JToolBar{

private FontNameComboBox fontNameSelector;
private FontSizeComboBox fontSizeSelector;
private JCheckBox italicButton, boldButton;
private boolean italic, bold;
private boolean visible;

public FontToolBar() {
super();
fontNameSelector = new FontNameComboBox();
add(fontNameSelector);
fontSizeSelector = new FontSizeComboBox();
fontSizeSelector.setSelectedIndex(6);
add(fontSizeSelector);
italicButton = new JCheckBox("I");
add(italicButton);
boldButton = new JCheckBox("B");
add(boldButton);
visible = true;
}

private void checkSelected() {
if(italicButton.isSelected()) {
italic = true;
} else {
italic = false;
}

if(boldButton.isSelected()) {
bold = true;
} else {
bold = false;
}
}

private class FontNameComboBox extends JComboBox {
private Font[] fonts;

FontNameComboBox() {
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
fonts = e.getAllFonts();
setEditable(false);
for(Font f : fonts) {
addItem(f.getFontName());
}
}
}

private class FontSizeComboBox extends JComboBox {
FontSizeComboBox() {
for(int i = 6; i < 121; i++) {
addItem(i);
}
}
}

public int getFontIndex() {
return fontNameSelector.getSelectedIndex();
}

public int getSizeIndex() {
return fontSizeSelector.getSelectedIndex();
}

public void setFontIndex(int index) {
fontNameSelector.setSelectedIndex(index);
}

public void setSizeIndex(int index) {
fontSizeSelector.setSelectedIndex(index);
}

public boolean isItalic() {
return italic;
}

public boolean isBold() {
return bold;
}

public void setItalic(boolean bool) {
italic = bool;
italicButton.setSelected(bool);
}

public void setBold(boolean bool) {
bold = bool;
boldButton.setSelected(bool);
}

public boolean isVisible() {
return visible;
}

public void setVisible(boolean bool) {
visible = bool;
}

public Font getSelectedFont() {
Font font;
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();
font = fonts[fontNameSelector.getSelectedIndex()];
int fontType;

checkSelected();

if(italic && bold){
fontType = Font.BOLD+Font.ITALIC;
} else if (italic) {
fontType = Font.ITALIC;
} else if (bold) {
fontType = Font.BOLD;
} else {
fontType = Font.PLAIN;
}

int fontSize = (int)fontSizeSelector.getSelectedItem();
font = font.deriveFont(fontType, (float) fontSize);
return font;
}

}

/**
* @author Simone Silini
* @version 0.1 31/07/2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
*/

package gui;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import menu.Menu;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class Window extends JFrame{

private Menu menu;
private Listener listener;
boolean edited;
private FontToolBar fontToolBar;
private ColorsToolBar colorsToolBar;
private JTextArea textPane;
private JScrollPane scrollPane;
private Timer timer;
private Color backgroundColor;
private Color textColor;
private String fileName = null;
private Image logo;

public Window() {
listener = new Listener();
backgroundColor = Color.WHITE;
textColor = Color.BLACK;
addWindowListener(new WListener());
setLayout(new BorderLayout());
edited = true;
menu = new Menu(listener);
setJMenuBar(menu);
fontToolBar = new FontToolBar();
add(fontToolBar, BorderLayout.NORTH);
colorsToolBar = new ColorsToolBar(textColor, backgroundColor);
add(colorsToolBar, BorderLayout.SOUTH);
textPane = new JTextArea();
textPane.setLineWrap(true);
textPane.setFont(new Font("Serif", Font.PLAIN, 100));
textPane.getDocument().addDocumentListener(new DocListener());
scrollPane = new JScrollPane(textPane);
add(scrollPane);
timer = new Timer(100, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
update();
}

});
timer.start();
setSize(800, 600);
setLocation(100, 100);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
logo = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/logo.jpg"));
setIconImage(logo);
setVisible(true);
}

public void updateToolBars() {
fontToolBar.setVisible(fontToolBar.isVisible());
colorsToolBar.setVisible(colorsToolBar.isVisible());
}

public void updateColors() {
textColor = colorsToolBar.getTextColor();
backgroundColor = colorsToolBar.getBackgroundColor();
}

public void update() {
updateColors();
updateToolBars();
textPane.setFont(fontToolBar.getSelectedFont());
textPane.setForeground(textColor);
textPane.setBackground(backgroundColor);
repaint();
}

public void paintComponent(Graphics g) {
super.paintComponents(g);
}

public void save() {
try {
PrintWriter saver = new PrintWriter(fileName);
saver.println("textColor|" + textColor.getRed() + "|" + textColor.getGreen() + "|" + textColor.getBlue());
saver.println("backgroundColor|" + backgroundColor.getRed() + "|" + backgroundColor.getGreen() + "|" + backgroundColor.getBlue());
saver.println("Font|" + fontToolBar.getFontIndex());
saver.println("Size|" + fontToolBar.getSizeIndex());
saver.println("Italic|" + fontToolBar.isItalic());
saver.println("Bold|" + fontToolBar.isBold());
saver.println("-------------------------------------------------------------------");
saver.println();
for(String line: textPane.getText().split("\n")) {
System.out.println(line);
saver.println(line);
}
saver.close();
} catch (Exception e) {
e.printStackTrace();
}
edited = false;
}

public void saveAs() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setMultiSelectionEnabled(false);
chooser.addChoosableFileFilter(new FileNameExtensionFilter("Only txt Files", "txt"));
chooser.setAcceptAllFileFilterUsed(false);
int choise = chooser.showSaveDialog(this);
if(choise == chooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getPath();
if(!fileName.endsWith(".txt")) fileName = fileName + ".txt";
save();
}
}

public void open() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setMultiSelectionEnabled(false);
chooser.setFileFilter(new FileNameExtensionFilter("Only txt Files", "txt"));
chooser.setAcceptAllFileFilterUsed(false);
int choise = chooser.showOpenDialog(this);

if(choise == chooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getPath();
StringBuffer text = new StringBuffer();
String line = "";
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
while((line = in.readLine()) != null)
{
String[] tokens = line.split("\|");
if(tokens[0].equalsIgnoreCase("backgroundColor")) {
backgroundColor = new Color(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]));
} else if (tokens[0].equalsIgnoreCase("textColor")) {
textColor = new Color(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]));
}else if (tokens[0].equalsIgnoreCase("font")) {
fontToolBar.setFontIndex(Integer.parseInt(tokens[1]));
}else if (tokens[0].equalsIgnoreCase("size")) {
fontToolBar.setSizeIndex(Integer.parseInt(tokens[1]));
}else if (tokens[0].equalsIgnoreCase("italic")) {
fontToolBar.setItalic(Boolean.parseBoolean(tokens[1]));
}else if (tokens[0].equalsIgnoreCase("bold")) {
fontToolBar.setBold(Boolean.parseBoolean(tokens[1]));
}else if (tokens[0].startsWith("---")) {

}else {
textPane.append(line + "n");
}
}
colorsToolBar.setTextColor(textColor);
colorsToolBar.setBackgroundColor(backgroundColor);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

private class Listener implements ActionListener {

@Override
public void actionPerformed(ActionEvent event) {

if(event.getActionCommand().equalsIgnoreCase("exit")) {
exiting();
} else if(event.getActionCommand().equalsIgnoreCase("open")){
open();
} else if(event.getActionCommand().equalsIgnoreCase("save")){
if(fileName == null) {
saveAs();
} else {
save();
}
} else if(event.getActionCommand().equalsIgnoreCase("saveas")){
saveAs();
} else if(event.getActionCommand().equalsIgnoreCase("fonttoolbar")){
boolean b = menu.getViewMenu().getFontToolbar().isSelected();
fontToolBar.setVisible(b);
} else if(event.getActionCommand().equalsIgnoreCase("colorstoolbar")){
colorsToolBar.setVisible(menu.getViewMenu().getColorsToolbar().isSelected());

}

}

}

private class DocListener implements DocumentListener {

@Override
public void insertUpdate(DocumentEvent e) {
edited = true;
}

@Override
public void removeUpdate(DocumentEvent e) {
edited = true;
}

@Override
public void changedUpdate(DocumentEvent e) {
edited = true;
}

}

private class WListener implements WindowListener {

public void windowOpened(WindowEvent e) {}

@Override
public void windowClosing(WindowEvent e) {
exiting();
}

@Override
public void windowClosed(WindowEvent e) {}

@Override
public void windowIconified(WindowEvent e) {}

@Override
public void windowDeiconified(WindowEvent e) {}

@Override
public void windowActivated(WindowEvent e) {}

@Override
public void windowDeactivated(WindowEvent e) {}

}

private void exiting() {
if(edited) {
int selection = JOptionPane.showConfirmDialog(this, "You didn't saved, are you sure you want to quit?", "Not Saved", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if(selection == JOptionPane.OK_OPTION) {
System.exit(0);
}
}else {
System.exit(0);
}
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {

Window window = new Window();
}
});
}

}

Liked it? Take a second to support Zamein on Patreon!
Precedente Zamein's Notepad Successivo Zamein's Paint v1.0

0 thoughts on “Zamein’s Notepad – Source Code

  1. Pingback: Zamein’s Notepad | Zamein's projects