-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImprovedTextEditor.java
More file actions
318 lines (280 loc) · 11.7 KB
/
Copy pathImprovedTextEditor.java
File metadata and controls
318 lines (280 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package src;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
// Class for the Improved Text Editor application
public class ImprovedTextEditor extends JFrame {
private JTextArea textArea;
// Constructor to initialize the text editor
public ImprovedTextEditor() {
setTitle("Improved Text Editor"); // Set the title of the window
setSize(600, 600); // Set the size of the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the close operation when the window is closed
// Set the look and feel of the text area
UIManager.put("TextArea.background", Color.BLACK); // Set background color
UIManager.put("TextArea.foreground", Color.WHITE); // Set text color
// Create a JTextArea for text input
textArea = new JTextArea();
textArea.setFont(new Font("Menlo", Font.PLAIN, 12)); // Set font style and size
JScrollPane scrollPane = new JScrollPane(textArea); // Create a scroll pane to contain the text area
add(scrollPane); // Add the scroll pane to the frame
textArea.setCaretColor(Color.WHITE); // Set the text cursor color to white
// Add line numbers
JTextArea lineNumbers = new JTextArea("1");
lineNumbers.setBackground(Color.DARK_GRAY);
lineNumbers.setForeground(Color.WHITE);
lineNumbers.setEditable(false);
scrollPane.setRowHeaderView(lineNumbers);
textArea.getDocument().addDocumentListener(new DocumentListener() {
public String getText() {
int caretPosition = textArea.getDocument().getLength();
Element root = textArea.getDocument().getDefaultRootElement();
String text = "1\n";
for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
text += i + "\n";
}
return text;
}
// Update line numbers when text is inserted
@Override
public void insertUpdate(DocumentEvent e) {
lineNumbers.setText(getText());
}
// Update line numbers when text is removed
@Override
public void removeUpdate(DocumentEvent e) {
lineNumbers.setText(getText());
}
// Update line numbers when text is changed
@Override
public void changedUpdate(DocumentEvent e) {
lineNumbers.setText(getText());
}
});
// Create menu bar and menus
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
// Sub-Items for the "File" JMenu
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save-As");
JMenuItem closeItem = new JMenuItem("Close");
JMenu editMenu = new JMenu("Edit");
JMenu fontMenu = new JMenu("Font");
// OPTIONAL ITEMS FOR "EDIT" JMenu
/*
JMenuItem boldItem = new JMenuItem("Bold");
JMenuItem italicItem = new JMenuItem("Italic");
*/
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (String font : fonts) {
fontMenu.add(new JMenuItem(font)).addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setFont(new Font(((JMenuItem) e.getSource()).getText(), Font.PLAIN, 12));
}
});
}
editMenu.add(fontMenu);
// Add "Italic" and "Bold" JMenuItem here*
// Search menu bar
JMenu searchMenu = new JMenu("Search");
final JTextField searchField = new JTextField(20);
searchField.setToolTipText("Type what to search and press Enter");
searchMenu.add(searchField);
JMenuItem findItem = new JMenuItem("Find");
findItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textArea.getText();
String searchText = searchField.getText().toLowerCase();
int pos = 0;
while ((pos = text.indexOf(searchText, pos)) >= 0) {
try {
textArea.getHighlighter().addHighlight(pos, pos + searchText.length(),
DefaultHighlighter.DefaultPainter);
pos += searchText.length();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
});
// Help menu for documentation
JMenu helpMenu = new JMenu("Help");
JMenuItem docsItem = new JMenuItem("Documentation");
docsItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().browse(new java.net.URI("https://github.com/JeninSutradhar"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
// Add action listeners for file menu items
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openFile();
}
});
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
});
closeItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Add items to file menu
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
// Add file menu to menu bar
menuBar.add(fileMenu);
// Add edit menu to menu bar
menuBar.add(editMenu);
// Add search menu to menu bar
searchMenu.add(findItem);
menuBar.add(searchMenu);
// Add help menu to menu bar
helpMenu.add(docsItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar); // Set the menu bar for the frame
// Apply syntax highlighting
applySyntaxHighlighting();
// Apply auto-indentation
textArea.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == '\n') {
autoIndent();
}
}
});
// Display word count
textArea.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
updateWordCount();
}
@Override
public void removeUpdate(DocumentEvent e) {
updateWordCount();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateWordCount();
}
});
}
// Method to open a file
private void openFile() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(selectedFile));
textArea.read(reader, null);
reader.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Error opening file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// Method to save a file
private void saveFile() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile));
textArea.write(writer);
writer.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// Method to apply syntax highlighting
private void applySyntaxHighlighting() {
SyntaxHighlighter.highlight(textArea);
}
// Method to auto-indent text
private void autoIndent() {
int caretPosition = textArea.getCaretPosition();
int lineStart = caretPosition;
while (lineStart > 0 && textArea.getText().charAt(lineStart - 1) != '\n') {
lineStart--;
}
String lineText = textArea.getText().substring(lineStart, caretPosition);
final int[] indentation = {0}; // Declare as final array to make it effectively final
for (int i = 0; i < lineText.length(); i++) {
if (Character.isWhitespace(lineText.charAt(i))) {
indentation[0]++;
} else {
break;
}
}
SwingUtilities.invokeLater(() -> {
textArea.insert("\n" + " ".repeat(indentation[0]), caretPosition);
});
}
// Method to update word count and display in the window title
private void updateWordCount() {
String text = textArea.getText();
int words = text.isEmpty() ? 0 : text.split("\\s+").length;
int characters = text.length();
int lines = textArea.getLineCount();
// Display word count, character count, and line count in the window title
setTitle("Text Editor - Words: " + words + ", Characters: " + characters + ", Lines: " + lines);
}
// Main method to start the application
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ImprovedTextEditor editor = new ImprovedTextEditor();
editor.setVisible(true);
});
}
}
/*
* THIS FEATURE MAY NOT WORK ON SOME SYSTEMS
*/
// Class for syntax highlighting
class SyntaxHighlighter {
// Method to highlight keywords in the text area
public static void highlight(JTextArea textArea) {
DefaultHighlighter highlighter = (DefaultHighlighter) textArea.getHighlighter();
DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
String[] keywords = {"if", "else", "for", "while", "switch", "case", "break", "continue", "return", "class", "public", "private", "protected"};
for (String keyword : keywords) {
highlightWord(textArea, keyword.toLowerCase(), painter); // Convert keyword to lowercase
}
}
// Method to highlight occurrences of a word in the text area
private static void highlightWord(JTextArea textArea, String word, DefaultHighlighter.DefaultHighlightPainter painter) {
String text = textArea.getText().toLowerCase(); // Convert text to lowercase
int pos = 0;
while ((pos = text.indexOf(word, pos)) >= 0) {
try {
textArea.getHighlighter().addHighlight(pos, pos + word.length(), painter);
// Change the foreground color
textArea.setSelectionColor(Color.GREEN); // Set Custom color here
pos += word.length();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}