Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package isizulu_spellchecker; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.filechooser.FileFilter; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import javax.swing.text.Highlighter.HighlightPainter; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; /** * * @author Norman_P */ public class Spellchecker extends javax.swing.JFrame { Model m; String text; String currentWord = ""; boolean language = true; //Markers int sentNo = 0;//Which sentence int wordNo = 0;//Which word in a sentence int pos = 0; //The word position in the text area boolean endOfText = false; boolean highlightSet = false; //Used to clear text area Highlighter highlighter; HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.PINK); ArrayList<String> once = new ArrayList<>(); ArrayList<String> all = new ArrayList<>(); /** * Creates new form Spell checker */ public Spellchecker() { m = new Model(); initComponents(); FileFilter docFilter = new MyCustomFilter(".docx", "Microsoft Word Documents"); FileFilter txtFilter = new MyCustomFilter(".txt", "Text Documents"); fileChooser.addChoosableFileFilter(docFilter); fileChooser.addChoosableFileFilter(txtFilter); textArea.addMouseListener(new PopupListener()); lmatters.setText(String.format("<html>%s<font color='red'>%s</font>@<font color='green'>%s</font></html>", "language", "matters", "ukzn")); cut.addActionListener(new DefaultEditorKit.CutAction()); copy.addActionListener(new DefaultEditorKit.CopyAction()); paste.addActionListener(new DefaultEditorKit.PasteAction()); popup.add(new JMenuItem(new DefaultEditorKit.CopyAction())); popup.add(new JMenuItem(new DefaultEditorKit.CutAction())); popup.add(new JMenuItem(new DefaultEditorKit.PasteAction())); textarea = new JTextArea(40, 50); textarea.setEditable(false); mainPanel = new JPanel(); mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mainPanel.setLayout(new BorderLayout(5, 5)); mainPanel.add(textarea, BorderLayout.CENTER); helpWindow = new JFrame("Help"); helpWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); helpWindow.getContentPane().add(mainPanel); helpWindow.pack(); helpWindow.setLocationByPlatform(true); helpWindow.setVisible(false); } /** * This method is called from within the constructor to initialise the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { fileChooser = new javax.swing.JFileChooser(); popup = new javax.swing.JPopupMenu(); run = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); textArea = new javax.swing.JTextArea(); ignoreOnce = new javax.swing.JButton(); ignoreAll = new javax.swing.JButton(); add = new javax.swing.JButton(); close = new javax.swing.JButton(); clear = new javax.swing.JButton(); instruction = new javax.swing.JLabel(); lmatters = new javax.swing.JLabel(); checkAll = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel5 = new javax.swing.JLabel(); saveCorrection = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); file = new javax.swing.JMenu(); open = new javax.swing.JMenuItem(); saveAs = new javax.swing.JMenuItem(); languageCheck = new javax.swing.JCheckBoxMenuItem(); exit = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); cut = new javax.swing.JMenuItem(); copy = new javax.swing.JMenuItem(); paste = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); help = new javax.swing.JMenuItem(); about_ = new javax.swing.JMenuItem(); fileChooser.setDialogTitle("Choose file"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("IsiZulu Spellchecker"); setLocation(new java.awt.Point(200, 50)); setMinimumSize(new java.awt.Dimension(890, 580)); setSize(new java.awt.Dimension(90, 0)); run.setText("Run"); run.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runActionPerformed(evt); } }); jScrollPane1.setAutoscrolls(true); jScrollPane1.setMinimumSize(new java.awt.Dimension(66, 16)); textArea.setColumns(20); textArea.setLineWrap(true); textArea.setRows(5); textArea.setWrapStyleWord(true); textArea.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); textArea.setMinimumSize(new java.awt.Dimension(60, 12)); textArea.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() { public void ancestorMoved(java.awt.event.HierarchyEvent evt) { } public void ancestorResized(java.awt.event.HierarchyEvent evt) { textAreaAncestorResized(evt); } }); textArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textAreaKeyTyped(evt); } }); jScrollPane1.setViewportView(textArea); ignoreOnce.setText("Ignore Once"); ignoreOnce.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ignoreOnceActionPerformed(evt); } }); ignoreAll.setText("Ignore All"); ignoreAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ignoreAllActionPerformed(evt); } }); add.setText("Add "); add.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addActionPerformed(evt); } }); close.setText("Close"); close.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeActionPerformed(evt); } }); clear.setText("Clear Text"); clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearActionPerformed(evt); } }); instruction.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N instruction.setForeground(new java.awt.Color(0, 0, 255)); instruction.setText("To begin: Type or paste text below or Click File->Open File... to load a file"); instruction.setDoubleBuffered(true); lmatters.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N lmatters.setText("Languagematters@UKZN"); checkAll.setText("Show All"); checkAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkAllActionPerformed(evt); } }); jLabel5.setForeground(new java.awt.Color(128, 128, 128)); jLabel5.setText("By: Norman Pilusa"); saveCorrection.setText("Save Correction"); saveCorrection.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveCorrectionActionPerformed(evt); } }); jLabel2.setIcon( new javax.swing.ImageIcon(getClass().getResource("/isizulu_spellchecker/resources/ukzn_logo.png"))); // NOI18N file.setText("File"); open.setText("Open file..."); open.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openActionPerformed(evt); } }); file.add(open); saveAs.setText("Save As..."); saveAs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsAsActionPerformed(evt); } }); file.add(saveAs); languageCheck.setSelected(true); languageCheck.setText("Use English"); languageCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { languageCheckActionPerformed(evt); } }); file.add(languageCheck); exit.setText("Exit"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); file.add(exit); jMenuBar1.add(file); editMenu.setText("Edit"); cut.setText("Cut"); cut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cutActionPerformed(evt); } }); editMenu.add(cut); copy.setText("Copy"); editMenu.add(copy); paste.setText("Paste"); editMenu.add(paste); jMenuBar1.add(editMenu); helpMenu.setText("Help"); help.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0)); help.setText("Help"); help.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpActionPerformed(evt); } }); helpMenu.add(help); about_.setText("About"); about_.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { about_ActionPerformed(evt); } }); helpMenu.add(about_); jMenuBar1.add(helpMenu); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup().addGap(386, 386, 386) .addComponent(lmatters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(298, 298, 298).addComponent(jLabel5).addGap(23, 23, 23)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(instruction, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout .createSequentialGroup() .addComponent( jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(close, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(saveCorrection, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(clear, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(add, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ignoreAll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ignoreOnce, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkAll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(run, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(26, 26, 26))))) .addGap(2, 2, 2))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addComponent(instruction) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(54, 54, 54) .addComponent(run, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(checkAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(42, 42, 42) .addComponent(ignoreOnce, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ignoreAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(add, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveCorrection, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(53, 53, 53).addComponent(close, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGap(31, 31, 31) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lmatters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5)) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void runActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runActionPerformed // TODO add your handling code here: text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.red); return; } else if (noErrors()) { if (language) { instruction.setText("No errors detected!"); } else { instruction.setText("Akukho maphutha atholakele"); } instruction.setForeground(Color.BLUE); return; } else { if (language) { instruction.setText("What do you want to do with this error?"); } else { instruction.setText("Ufuna ukwenzani ngaleli phutha?"); } instruction.setForeground(Color.BLUE); pos = 0; wordNo = 0; sentNo = 0; } try { String[] sentences = text.split("\n"); String[] words; int start = 0; int end = 0; boolean active = true; //Input is just a sentence or word if (sentences.length < 2) { words = text.split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) {//incorrect word start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; break; } wordNo += 1; pos += word.length() + 1; } //Input is a two or more lines } else { while (sentNo < sentences.length && active) { words = sentences[sentNo].split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) { start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; active = false; break; } wordNo += 1; pos += word.length() + 1; } //Jump to next sentence if (wordNo >= words.length) { wordNo = 0; sentNo++; } } } } catch (BadLocationException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); } highlightSet = true; }//GEN-LAST:event_runActionPerformed private void ignoreOnceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ignoreOnceActionPerformed // TODO add your handling code here: Ignore once text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); String[] sentences = text.split("\n"); try { String[] words; int start = 0; int end = 0; boolean active = true; if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (language) { instruction.setText("Click Run first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (pos >= text.length()) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); return; } else { once.add(currentWord); } //Input is just a sentence or word if (sentences.length < 2) { words = text.split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) {//incorrect word start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; break; } wordNo += 1; pos += word.length() + 1; } //Input is a two or more lines } else { while (sentNo < sentences.length && active) { words = sentences[sentNo].split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) { start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; active = false; break; } wordNo += 1; pos += word.length() + 1; } //Jump to next sentence if (wordNo >= words.length) { wordNo = 0; sentNo++; } } } } catch (BadLocationException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); } if (pos >= text.length() && sentNo >= sentences.length) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); currentWord = ""; return; } highlightSet = true; }//GEN-LAST:event_ignoreOnceActionPerformed private void ignoreAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ignoreAllActionPerformed // TODO add your handling code here: Ignore All text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); String[] sentences = text.split("\n"); try { String[] words; int start = 0; int end = 0; boolean active = true; if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (language) { instruction.setText("Click Run first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (pos >= text.length()) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); if (highlightSet) { if (!all.contains(currentWord)) { all.add(currentWord); } highlightSet = false; } return; } else { all.add(currentWord); } //Input is just a sentence or word if (sentences.length < 2) { words = text.split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) {//incorrect word start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; break; } wordNo += 1; pos += word.length() + 1; } //Input is a two or more lines } else { while (sentNo < sentences.length && active) { words = sentences[sentNo].split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) { start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; active = false; break; } wordNo += 1; pos += word.length() + 1; } //Jump to next sentence if (wordNo >= words.length) { wordNo = 0; sentNo++; } } } } catch (BadLocationException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); } if (pos >= text.length() && sentNo >= sentences.length) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); currentWord = ""; return; } highlightSet = true; }//GEN-LAST:event_ignoreAllActionPerformed private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed // TODO add your handling code here: Add to dictionary text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); String[] sentences = text.split("\n"); try { String[] words; int start = 0; int end = 0; boolean active = true; if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (language) { instruction.setText("Click Run first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (pos >= text.length()) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); if (highlightSet) {//one word text m.addWord(currentWord); highlightSet = false; } return; } else { m.addWord(currentWord);//Writes the word to the user's dictionary } //Input is just a sentence or word if (sentences.length < 2) { words = text.split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) {//incorrect word start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; break; } wordNo += 1; pos += word.length() + 1; } //Input is a two or more lines } else { while (sentNo < sentences.length && active) { words = sentences[sentNo].split(" "); //iterate through words for (int i = wordNo; i < words.length; i++) { String word = words[i]; if (!all.contains(word) && !m.check(word)) { start = text.indexOf(word, pos); end = start + word.length(); highlighter.addHighlight(start, end, painter); currentWord = text.substring(start, end); pos += word.length() + 1; //move to next word then stop wordNo += 1; active = false; break; } wordNo += 1; pos += word.length() + 1; } //Jump to next sentence if (wordNo >= words.length) { wordNo = 0; sentNo++; } } } } catch (BadLocationException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); } if (pos >= text.length() && sentNo >= sentences.length) { if (language) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText("Usufike esiphethweni sombhalo wakho. Cofa usebenzisa ukuze uhlole futhi"); instruction.setForeground(Color.BLUE); currentWord = ""; return; } highlightSet = true; }//GEN-LAST:event_addActionPerformed private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_closeActionPerformed private void clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearActionPerformed // TODO add your handling code here: //Resets globals used by other buttons such as ignoreAll if (textArea.getText().length() == 0) { if (language) instruction.setText("Nothing to clear"); else instruction.setText("Akukho okucishwayo"); instruction.setForeground(Color.red); } else { if (language) instruction.setText("Text cleared! Start over."); else instruction.setText("Umbhalo usucishiwe! Qala kabusha."); instruction.setForeground(Color.BLUE); pos = 0; sentNo = 0; wordNo = 0; textArea.setText(""); } }//GEN-LAST:event_clearActionPerformed private void checkAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkAllActionPerformed // TODO add your handling code here: text = textArea.getText(); highlighter = textArea.getHighlighter(); if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (language) { instruction.setText("Click Run first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (noErrors()) { if (language) instruction.setText("No errors detected!"); else instruction.setText("Akukho maphutha atholakele"); instruction.setForeground(Color.BLUE); return; } else { if (language) instruction.setText("Click Run to process errors one at a time"); else instruction.setText("Cofa uSebenzisa ukuze ubheke iphutha ngalinye ngesikhathi"); instruction.setForeground(Color.BLUE); } try { String[] sentences = text.split("\n"); String[] words; int start; int end; int position = 0; int sentence = 0; //Input is just a sentence or word if (sentences.length < 2) { words = text.split(" "); //iterate through words for (String word : words) { System.out.println(word); if (!all.contains(word) && !m.check(word)) {//incorrect word start = text.indexOf(word, position); end = start + word.length(); highlighter.addHighlight(start, end, painter); } position += word.length() + 1; } //Input is a two or more lines } else { while (sentence < sentences.length) { words = sentences[sentence].split(" "); //iterate through words for (String word : words) { if (!all.contains(word) && !m.check(word)) { start = text.indexOf(word, position); end = start + word.length(); highlighter.addHighlight(start, end, painter); } position += word.length() + 1; } sentence++; } } } catch (BadLocationException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); } highlightSet = true; //Resets globals used by other buttons such as ignoreAll pos = 0; sentNo = 0; wordNo = 0; }//GEN-LAST:event_checkAllActionPerformed private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed // TODO add your handling code here: int returnVal = fileChooser.showOpenDialog(this); if (language) instruction.setText("Click run to check for errors"); else instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha"); instruction.setForeground(Color.BLUE); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String name = file.getName(); String ext = name.substring(name.indexOf("."), name.length()); try { // What to do with the file, e.g. display it in a TextArea if (highlightSet) { highlighter.removeAllHighlights(); } if (name.endsWith(".docx")) { FileInputStream fis = new FileInputStream(file.getAbsolutePath()); XWPFDocument docx = new XWPFDocument(fis); List<XWPFParagraph> pars = docx.getParagraphs(); String toDisplay = ""; for (XWPFParagraph para : pars) { toDisplay += para.getText() + "\n"; } textArea.setText(toDisplay); text = textArea.getText(); } else { textArea.read(new FileReader(file.getAbsolutePath()), null); text = textArea.getText(); //for controlling the displayed text } } catch (IOException ex) { System.out.println("problem accessing file" + file.getAbsolutePath()); } } //Resets globals used by other buttons such as ignoreAll pos = 0; sentNo = 0; wordNo = 0; }//GEN-LAST:event_openActionPerformed private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_exitActionPerformed private void about_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_about_ActionPerformed // TODO add your handling code here: if (language) { JOptionPane.showMessageDialog(null, "This IsiZulu spellchecker is based on the\nIsiZulu National Corpus from ULPDO at UKZN.\nDesigned by the department of Computer Science at UCT .", "About", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Lensiza lokuhlola ukupelwa kwamagama isuselwe\\ kuKhophasi Kazwelonke yesiZulu ye-ULPDO e-UKZN\\ Yakhiwe umnyango wesayensi yamakhompyutha e-UCT.", "Mayelana", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_about_ActionPerformed private void textAreaAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_textAreaAncestorResized // TODO add your handling code here: }//GEN-LAST:event_textAreaAncestorResized private void saveAsAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsAsActionPerformed // TODO add your handling code here: int returnVal = fileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { // What to do with the file, e.g. display it in a TextArea if (highlightSet) { highlighter.removeAllHighlights(); } if (file.getName().endsWith(".docx")) { XWPFDocument document = new XWPFDocument(); XWPFParagraph tmpParagraph = document.createParagraph(); XWPFRun tmpRun = tmpParagraph.createRun(); tmpRun.setText(textArea.getText()); tmpRun.setFontSize(12); document.write(new FileOutputStream(new File(file.getPath()))); } else { textArea.write(new FileWriter(file.getAbsolutePath()));//this file has no extension } } catch (IOException ex) { System.out.println("problem accessing file" + file.getAbsolutePath()); } } }//GEN-LAST:event_saveAsAsActionPerformed private void helpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpActionPerformed /*/ TODO add your handling code here: JOptionPane.showMessageDialog(null, String.format("%s\n%s\n\"http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html\"", "Instructions are shown above the text area.", "You might have to download jre here:"), "Quick help", JOptionPane.INFORMATION_MESSAGE); //JOptionPane.showMessageDialog(null,"Instructions are shown above the text area.\nI hope this helps you.","Quick help",JOptionPane.INFORMATION_MESSAGE); */ try { InputStream ins = Isizulu_Spellchecker.class.getResourceAsStream("resources/Instructions.txt"); BufferedReader insReader = new BufferedReader(new InputStreamReader(ins)); textarea.read(insReader, ins); helpWindow.setVisible(true); } catch (IOException ex) { Logger.getLogger(Spellchecker.class.getName()).log(Level.SEVERE, null, ex); System.out.println("File not found"); } }//GEN-LAST:event_helpActionPerformed private void saveCorrectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCorrectionActionPerformed // TODO add your handling code here: text = textArea.getText(); highlighter = textArea.getHighlighter(); if (text.length() == 0) { if (language) { instruction.setText("You are trying to save an empty file!"); } else { instruction.setText("Uzama ukulondoloza ifayela elingenalutho!"); } instruction.setForeground(Color.red); } else { saveCorrectionActionPerformed(evt); } }//GEN-LAST:event_saveCorrectionActionPerformed private void cutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cutActionPerformed private void textAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textAreaKeyTyped // TODO add your handling code here: int len = textArea.getText().length(); if (highlightSet && len != 0) { if (language) { instruction .setText("Click run to check the correctness of your changes or to continue to next error"); } else { instruction.setText( "Cofa usebenzisa ukuze uhlole ubunjalo kwezinguquko ozenzile noma udlulele ephutheni elilandelayo "); } instruction.setForeground(Color.blue); highlighter.removeAllHighlights(); highlightSet = false; } else if (len == 0) { if (language) { instruction.setText("Type or paste text below or Click File -> Open file... to load a file!"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } instruction.setForeground(Color.blue); if (highlightSet) { highlightSet = false; } } else { if (language) { instruction.setText("Click run to check for errors"); } else { instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha"); } instruction.setForeground(Color.blue); } }//GEN-LAST:event_textAreaKeyTyped private void languageCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languageCheckActionPerformed // TODO add your handling code here: text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); language = !language; if (language) { languageCheck.setText("Use English"); about_.setText("About"); add.setText("Add"); checkAll.setText("Show All"); saveCorrection.setText("Save Correction"); saveAs.setText("Save As..."); run.setText("Run"); paste.setText("Paste"); cut.setText("Cut"); copy.setText("Copy"); open.setText("Open"); ignoreAll.setText("Ignore All"); ignoreOnce.setText("Ignore Once"); help.setText("Help"); helpMenu.setText("Help"); file.setText("File"); exit.setText("Exit"); close.setText("Close"); clear.setText("Clear Text"); editMenu.setText("Edit"); if (textArea.getText().length() == 0) { instruction .setText("To begin: Type or paste text below or Click File->Open File... to load a file"); } else { instruction.setText("Click run to check for errors"); } } else { this.setBounds(0, 0, 1100, 748); languageCheck.setText("ulimi le singisi"); about_.setText("Mayelana"); add.setText("Engeza"); checkAll.setText("Khombisa Konke"); saveCorrection.setText("Londoloza Okulungisiwe"); saveAs.setText("Londoloza ngo"); run.setText("Sebenzisa"); paste.setText("Namathisela"); cut.setText("Sika"); copy.setText("Qopha"); open.setText("Vula ifayela"); ignoreAll.setText("Ziba Konke"); ignoreOnce.setText("Ziba Kanye"); help.setText("Usizo"); helpMenu.setText("Usizo"); file.setText("iFayela"); exit.setText("Phuma"); close.setText("Vala"); clear.setText("Cisha Umbhalo"); editMenu.setText("Lungisa"); if (text.length() == 0) { instruction.setText( "Ukuze uqale: Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } else { instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha"); } } }//GEN-LAST:event_languageCheckActionPerformed /* * Checks for all errors */ private boolean noErrors() { String[] sentences = textArea.getText().split("\n"); String[] words; int sentence = 0; if (sentences.length < 2) { words = textArea.getText().split(" "); //iterate through words for (String word : words) { if (!all.contains(word) && !m.check(word)) {//incorrect word return false; } } //Input is a two or more lines } else { while (sentence < sentences.length) { words = sentences[sentence].split(" "); //iterate through words for (String word : words) { if (!all.contains(word) && !m.check(word)) { return false; } } sentence++; } } return true; } private class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseReleased(MouseEvent e) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Spellchecker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Spellchecker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Spellchecker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Spellchecker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Spellchecker().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem about_; private javax.swing.JButton add; private javax.swing.JButton checkAll; private javax.swing.JButton clear; private javax.swing.JButton close; private javax.swing.JMenuItem copy; private javax.swing.JMenuItem cut; private javax.swing.JMenu editMenu; private javax.swing.JMenuItem exit; private javax.swing.JMenu file; private javax.swing.JFileChooser fileChooser; private javax.swing.JMenuItem help; private javax.swing.JMenu helpMenu; private javax.swing.JButton ignoreAll; private javax.swing.JButton ignoreOnce; private javax.swing.JLabel instruction; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel5; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JCheckBoxMenuItem languageCheck; private javax.swing.JLabel lmatters; private javax.swing.JMenuItem open; private javax.swing.JMenuItem paste; private javax.swing.JPopupMenu popup; private javax.swing.JButton run; private javax.swing.JMenuItem saveAs; private javax.swing.JButton saveCorrection; private javax.swing.JTextArea textArea; // End of variables declaration//GEN-END:variables private javax.swing.JFrame helpWindow; private JPanel mainPanel; private JTextArea textarea; }