Using Java to Build a Simple Text Editor Application
- Create menu, contextual menu
- Using toolbox component
- Using JTextPane
- Understand
JFileChooser
, JColorChooser
Background
- Basic Java UI component
- Read/write file
Code
Load all system font on font combobox
:
private void loadFont() {
GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = gEnv.getAvailableFontFamilyNames();
ComboBoxModel model = new DefaultComboBoxModel(fontNames);
jcbFont.setModel(model);
}?
When user selects font and size, we will be setting font and size for textpane
component:
private void jcbFontActionPerformed(java.awt.event.ActionEvent evt) {
jTextPane1.setFont(new Font(jcbFont.getSelectedItem().toString(),
Font.PLAIN, Integer.parseInt(jcbSelectSize.getSelectedItem().toString())));
}
private void jcbSelectSizeActionPerformed(java.awt.event.ActionEvent evt) {
String getSize = jcbSelectSize.getSelectedItem().toString();
Font f = jTextPane1.getFont();
jTextPane1.setFont(new Font(f.getFontName(),
f.getStyle(), Integer.parseInt(getSize)));
}
JColorChooser
API of Java swing helps us get a color from system color dialog, using code below for ActionPerformed
event of color button.
private void btnSelectColorActionPerformed(java.awt.event.ActionEvent evt) {
Color jColor = selectColor;
if ((jColor = JColorChooser.showDialog(this, "Select color", jColor)) != null) {
selectColor = jColor;
jTextPane1.setForeground(selectColor);
}
}
RTFEditorKit Can Help to Reading Formatted Text on JTextPane and Write Down File System with Rich Text Format
When user clicks on Save button or save as menu:
private void save() {
JFileChooser file = new JFileChooser();
TextFilter filter = new TextFilter();
file.setFileFilter(filter);
String fileName = "";
if (file.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
fileName = file.getSelectedFile().getAbsolutePath();
StyledDocument doc = (StyledDocument) jTextPane1.getDocument();
RTFEditorKit kit = new RTFEditorKit();
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(fileName));
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Err:" + e.toString());
}
} else {
return;
}
}
Handing button Open file or menu Open file as:
private void open() {
JFileChooser file = new JFileChooser();
TextFilter filter = new TextFilter();
file.setFileFilter(filter);
String fileName = "";
if (file.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
fileName = file.getSelectedFile().getAbsolutePath();
} else {
return;
}
RTFEditorKit rtf = new RTFEditorKit();
try {
FileInputStream fi = new FileInputStream(fileName);
rtf.read(fi, jTextPane1.getDocument(), 0);
fi.close();
} catch (Exception e) {
System.out.println("err:" + e.toString());
}
}?
Points of Interest
This is just demo Java beginner.
Maybe, see step by step video ==>> here <<==