Author Topic: [Java Source] Theify Java Text Editor & JFontChooser  (Read 1677 times)

0 Members and 1 Guest are viewing this topic.

Offline theifyppl

  • Serf
  • *
  • Posts: 44
  • Cookies: 20
    • View Profile
[Java Source] Theify Java Text Editor & JFontChooser
« on: July 08, 2013, 05:39:42 am »
Hello EZ,

I was going through some old projects of mine, and I found a text editor I programmed in Java from awhile back.  I just went through the forums I posted this on back then, and it seems it dates back to August of 2010.  Anyway, I coded this text editor just for fun and practice with GUI applications in Java. The project has two parts: the text editor and the font chooser dialogue.  Swing does not include a dialogue for font choosing, so I coded my own for this project.  Again, this is from 2010.

JFontChooser:

This is a subclass of JDialog, and works a lot like a JFileChooser or JColorChooser (with small differences, of course). It has full support for font color, and detects all the font families currently installed on your system, whatever OS you might have installed.

Here is the class file (I rushed through it and commented it a tiny bit):

Code: (java) [Select]
package textEdit;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


@SuppressWarnings("serial")
public class JFontChooser extends JDialog implements ActionListener, ListSelectionListener{

private JList fontList; //declare all GUI components, etc
private DefaultListModel fontListModel;
private JScrollPane fontListScroller;

private JList styleList;
private DefaultListModel styleListModel;
private JScrollPane styleListScroller;

private JList sizeList;
private DefaultListModel sizeListModel;
private JScrollPane sizeListScroller;

private JButton chooseColorButton;
private JButton OK;
private JButton cancelButton;
private JLabel sampleLabel;

public static final int APPROVED = 0; //will be used to see whether the cancel button
public static final int CANCELED = 1; //or OK button was pressed
public int result; //will contain either APPROVED or CANCELED

private String[] availableFonts; //will filter in all available fonts on the system

private Color newColor; //new font color gathered from Dialog
private Font newFont; //new font gathered from Dialog

private String currentFontFace; //these three are used for constructing the new font
private int currentFontStyle;
private int currentFontSize;

public JFontChooser(JFrame parent, String title) { //constructor #1

super(parent, title, true);
setupGUI();

}

public JFontChooser() { // constructor #2

super();
setupGUI();

}

public void showFontDialog() { //makes Dialog visible
this.setVisible(true);
}

private void setupGUI() { //builds GUI, but does not make it visible

this.setBounds(400, 150, 400, 330);
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//this.setLayout(new GridLayout(2, 3, 10, 10));
this.setLayout(null);

fontListModel = new DefaultListModel();
fontListModel.addElement("Serif");
fontListModel.addElement("Sans-serif");
fontListModel.addElement("Monospaced");
fontListModel.addElement("Dialog");
fontListModel.addElement("DialogInput");


availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

for(int i = 0; i < availableFonts.length; i++) {

fontListModel.addElement(availableFonts[i]);

}

fontList = new JList(fontListModel);
fontList.setSelectedIndex(0);
fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontListScroller = new JScrollPane(fontList);

styleListModel = new DefaultListModel();
styleListModel.addElement("Plain");
styleListModel.addElement("Bold");
styleListModel.addElement("Italic");
styleListModel.addElement("BoldItalic");

styleList = new JList(styleListModel);
styleList.setSelectedIndex(0);
styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
styleListScroller = new JScrollPane(styleList);

sizeListModel = new DefaultListModel();
sizeListModel.addElement("8");
sizeListModel.addElement("9");
sizeListModel.addElement("10");
sizeListModel.addElement("11");
sizeListModel.addElement("12");
sizeListModel.addElement("14");
sizeListModel.addElement("16");
sizeListModel.addElement("18");
sizeListModel.addElement("20");
sizeListModel.addElement("24");
sizeListModel.addElement("28");
sizeListModel.addElement("32");
sizeListModel.addElement("36");
sizeListModel.addElement("48");
sizeListModel.addElement("72");

sizeList = new JList(sizeListModel);
sizeList.setSelectedIndex(3);
sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sizeListScroller = new JScrollPane(sizeList);

chooseColorButton = new JButton("Color...");
chooseColorButton.addActionListener(this);
OK = new JButton("OK");
OK.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);

sampleLabel = new JLabel();
sampleLabel.setText("Sample!");

fontList.addListSelectionListener(this);
styleList.addListSelectionListener(this);
sizeList.addListSelectionListener(this);

this.add(fontListScroller);
this.add(styleListScroller);
this.add(sizeListScroller);
this.add(chooseColorButton);
this.add(OK);
this.add(cancelButton);
this.add(sampleLabel);

fontListScroller.setBounds(20, 20, 113, 148);
styleListScroller.setBounds(163, 20, 93, 148);
sizeListScroller.setBounds(286, 20, 73, 148);
chooseColorButton.setBounds(20, 250, 90, 30);
OK.setBounds(190, 250, 90, 30);
cancelButton.setBounds(295, 250, 90, 30);
sampleLabel.setBounds(100, 160, 400, 80);

}

public void actionPerformed(ActionEvent evt) {

String source = evt.getActionCommand();

if(source.equals("Color...")) { //set new font color using JColorChooser

newColor = JColorChooser.showDialog(this, "Choose your font color!", null);
sampleLabel.setForeground(newColor);

}

if(source.equals("OK")) { //set result to APPROVED and close dialog

result = APPROVED;
this.dispose();
}

if(source.equals("Cancel")) { //set result to CANCELED and close dialog

result = CANCELED;
this.dispose();

}
}

public Color getNewColor() { //getter for the new font color

return newColor;

}

public Font getNewFont() { //getter for the new font

return newFont;

}

public void valueChanged(ListSelectionEvent arg0) { //selection listener for the JLists
//sets new font and displays it in
//the sample label

currentFontFace = (String) fontList.getSelectedValue();
currentFontStyle = styleList.getSelectedIndex();
currentFontSize = Integer.parseInt((String) sizeList.getSelectedValue());

newFont = new Font(currentFontFace, currentFontStyle, currentFontSize);

sampleLabel.setFont(newFont);

}

}

And here is a picture:



Usage with a JTextArea:

Code: (java) [Select]
JFontChooser fontChooser = new JFontChooser(myJFrame, "Choose your font!");
fontChooser.showFontDialog();
if(fontChooser.result == JFontChooser.APPROVED) {

textarea.setFont(fontChooser.getNewFont());
textarea.setForeground(fontChooser.getNewColor());

}



Theify's Java Text Editor:

Code: (java) [Select]
package textEdit;
import javax.swing.*; //import errything
import javax.swing.filechooser.FileNameExtensionFilter;


import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;

import textEdit.JFontChooser;

@SuppressWarnings("serial")
public class TextEditorGUI extends JFrame implements ActionListener{


private static String fileName = "Untitled"; //declare GUI components and some others
private static JFrame window;
private static JTextArea textarea;
private static JPanel content;
private JScrollPane scroller;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem openFile;
private JMenuItem saveFile;
private JMenuItem saveAsFile;
private JMenuItem exitFile;
private JMenu formatMenu;
private JMenuItem fontFormat;
private JMenuItem backgroundColorFormat;
private JCheckBoxMenuItem wordWrapFormat;
private static JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
private JFontChooser fontChooser;
private static int returnVal;
private boolean hasBeenSaved = false;
private Color backColor;

public static void main(String[] args) { //basically, initiate the program

window = new TextEditorGUI();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);

}

public TextEditorGUI() { //constructor, no args...setup GUI

super(fileName + " - Theify's Java Text Editor");
this.setSize(new Dimension(700, 600));
this.setLocation(300, 100);

fontChooser = new JFontChooser(window, "Choose your font!");
content = new JPanel();
textarea = new JTextArea();
textarea.setLineWrap(true);
textarea.addKeyListener(new changedListener());
scroller = new JScrollPane(textarea);
content.setLayout(new BorderLayout());
content.add(scroller, BorderLayout.CENTER);

menuBar = new JMenuBar();

fileMenu = new JMenu("File");
openFile = new JMenuItem("Open");
openFile.addActionListener(this);
saveFile = new JMenuItem("Save");
saveFile.addActionListener(this);
saveAsFile = new JMenuItem("Save As...");
saveAsFile.addActionListener(this);
exitFile = new JMenuItem("Exit");
exitFile.addActionListener(this);

fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(saveAsFile);
fileMenu.add(exitFile);
menuBar.add(fileMenu);

formatMenu = new JMenu("Format");
fontFormat = new JMenuItem("Font");
fontFormat.addActionListener(this);
backgroundColorFormat = new JMenuItem("Back-Color");
backgroundColorFormat.addActionListener(this);
wordWrapFormat = new JCheckBoxMenuItem("Word Wrap");
wordWrapFormat.addActionListener(this);
wordWrapFormat.setSelected(true);

formatMenu.add(fontFormat);
formatMenu.add(backgroundColorFormat);
formatMenu.add(wordWrapFormat);
menuBar.add(formatMenu);

add(content);
this.setJMenuBar(menuBar);

FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
chooser.setFileFilter(filter);
}



public void actionPerformed(ActionEvent evt) { //when any menu item is pressed

Object source = evt.getActionCommand();

if(source.equals("Open")) { //use JFileChooser to select a file, and open it

if(hasBeenSaved == false) { //check if the current file has been saved and confirm the user's actions

String message = "Opening a new file will disregard any unsaved changes made to your current file.  Continue?";
String title = "Continue?";
returnVal = JOptionPane.showConfirmDialog(window, message, title, JOptionPane.YES_NO_OPTION);
if(returnVal == JOptionPane.NO_OPTION) {
return;
}
else if(returnVal == JOptionPane.YES_OPTION) {

try {
OpenFile();
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(window, "File Not Found.");
}
}
}
else {
try {
OpenFile();
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(window, "File Not Found.");
}
}
}

if(source.equals("Save")) { //check if the current file has been saved, and save

if(fileName == "Untitled") SaveAsFileProc();
else SaveFileProc(fileName);

}

if(source.equals("Save As...")) { //run saveAs function

SaveAsFileProc();

}

if(source.equals("Exit")) { //exit

System.exit(0);

}

if(source.equals("Font")) { //use JFontChooser to select and set a new font/font color

fontChooser.showFontDialog();
if(fontChooser.result == JFontChooser.APPROVED) {

textarea.setFont(fontChooser.getNewFont());
textarea.setForeground(fontChooser.getNewColor());

}

}


if(source.equals("Back-Color")) { //use JColorChooser to set the back-color of the textarea

backColor = JColorChooser.showDialog(window, "Choose a color!", Color.black);
textarea.setBackground(backColor);

}

if(source.equals("Word Wrap")) { //on/off switch for word wrap

if(textarea.getLineWrap() == true) textarea.setLineWrap(false);
else textarea.setLineWrap(true);

}

}

void OpenFile() throws FileNotFoundException { //open file function

returnVal = chooser.showOpenDialog(window); //use JFileChooser
if(returnVal == JFileChooser.APPROVE_OPTION) {

File newFile = chooser.getSelectedFile();

fileName = newFile.getPath();
hasBeenSaved = true;
saveFile.setEnabled(false);
resetWindowTitle();

FileReader fr = new FileReader(newFile); //use FileReader and BufferedReader
BufferedReader br = new BufferedReader(fr);
String nextLine = null;
textarea.setText(null);

try { //read file line by line into textarea
while((nextLine = br.readLine()) != null) {

textarea.append(nextLine + "\n");

}

}
catch (IOException e) {
JOptionPane.showMessageDialog(window, "IO Exception.");
}
}
}

void SaveFileProc(String fileName2) { //save file using FileWriter and BufferedWriter

FileWriter file;
try {
file = new FileWriter(fileName2);

BufferedWriter out = new BufferedWriter(file);

//save line by line
StringReader sr = new StringReader(textarea.getText());
BufferedReader br = new BufferedReader(sr);
String nextLine = "";
while ((nextLine = br.readLine()) != null){ //write it out line by line
out.write(nextLine);
out.newLine();
}

out.close();

hasBeenSaved = true;
saveFile.setEnabled(false);

}
catch (IOException e) {
JOptionPane.showMessageDialog(window, "IO Exception.");
}
}

void SaveAsFileProc() { //use JFileChooser to select file to save as, and use SaveFileProc

returnVal = chooser.showSaveDialog(window);
if(returnVal == JFileChooser.APPROVE_OPTION) {

File newFile = chooser.getSelectedFile();
fileName = newFile.getPath();
resetWindowTitle();

SaveFileProc(fileName);
}
}

void resetWindowTitle() {

window.setTitle(fileName + " - Theify's Java Text Editor");

}



public class changedListener implements KeyListener { //whenever a key is typed, file is declared unsaved

public void keyPressed(KeyEvent evt) { }
public void keyReleased(KeyEvent evt) { }
public void keyTyped(KeyEvent evt) {

if(hasBeenSaved == true) hasBeenSaved = false;
if(saveFile.isEnabled() == false) saveFile.setEnabled(true);
}
}
}

Picture (from 2010):





Anyway, that's it.  The only reason I decided to post this old project after I dug it up is because I thought it might have some educational value.  It shows how to go about creating GUI applications in Java, along with click event handling, etc.  Let me know what you think!

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: [Java Source] Theify Java Text Editor & JFontChooser
« Reply #1 on: July 08, 2013, 09:58:32 am »
I can remember that I have already seen that on Haxme. Because of that and because of its age I won't go through the code in detail.
It's a good exercise. Everyone who has no idea what to do, do something like this. ;)