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 IsiXhosa_spellchecker; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; 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.ButtonGroup; 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; XhosaModel xm; 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()); 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); //mainPanel.setMaximumSize(700, 0x2bc); this.setSize(400, 700); helpWindow = new JFrame("Help"); helpWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); helpWindow.getContentPane().add(mainPanel); helpWindow.pack(); helpWindow.setLocationByPlatform(true); helpWindow.setVisible(false); helpWindow.setSize(400, 450); ButtonGroup group = new ButtonGroup(); group.add(jRadioButton1); group.add(jRadioButton2); /**ButtonGroup langGroup = new ButtonGroup(); langGroup.add(jRadioButton3); langGroup.add(jRadioButton4);**/ if (jRadioButton1.isSelected()) { instruction.setText("To begin: Type or paste text below or click Open file to load file"); } else { instruction.setText( "Bhala noma namathelisela umbhalo olapha ngezansi noma > Cofa kuFayili > Vula ifayela..ukuze ufake ifayela."); } } /** * 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(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); label1 = new java.awt.Label(); 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.setIcon(new javax.swing.ImageIcon( getClass().getResource("/IsiXhosa_spellchecker/resources/spellcheck.png"))); // NOI18N run.setToolTipText("Check spelling errors"); 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.setToolTipText("Ignore the error"); ignoreOnce.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ignoreOnceActionPerformed(evt); } }); ignoreAll.setText("Ignore All"); ignoreAll.setToolTipText("Ignore all errors"); ignoreAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ignoreAllActionPerformed(evt); } }); add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IsiXhosa_spellchecker/resources/dict.png"))); // NOI18N add.setToolTipText("Add word to dictionary"); 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.setIcon( new javax.swing.ImageIcon(getClass().getResource("/IsiXhosa_spellchecker/resources/delete.png"))); // NOI18N clear.setToolTipText("Clear the textbox"); 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 Open File to load a file"); instruction.setDoubleBuffered(true); jLabel2.setIcon( new javax.swing.ImageIcon(getClass().getResource("/IsiXhosa_spellchecker/resources/uct_logo.png"))); // NOI18N jButton4.setBackground(new java.awt.Color(111, 190, 227)); jButton4.setText("Exit"); jButton4.setToolTipText("Close application"); jButton4.setName("exit"); // NOI18N jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton3.setBackground(new java.awt.Color(111, 190, 227)); jButton3.setText("Help"); jButton3.setToolTipText("Instruction to use tool"); jButton3.setName("help"); // NOI18N jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton2.setBackground(new java.awt.Color(111, 190, 227)); jButton2.setText("Save file"); jButton2.setToolTipText("Save the text file"); jButton2.setName("save_file"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton1.setBackground(new java.awt.Color(111, 190, 227)); jButton1.setText("Open file"); jButton1.setToolTipText("Open file from your machine"); jButton1.setName("open_file"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jRadioButton1.setSelected(true); jRadioButton1.setText("English"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jRadioButton2.setText("IsiXhosa"); jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); label1.setText("Interface language"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup().addGap(106, 106, 106).addComponent(jSeparator1)) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26))) .addGap(2, 2, 2)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addComponent(jLabel2).addGap(46, 46, 46) .addComponent(jButton1).addGap(18, 18, 18).addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent( jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(instruction, javax.swing.GroupLayout.PREFERRED_SIZE, 1726, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout .createSequentialGroup().addGap(12, 12, 12).addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 662, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout .createSequentialGroup().addComponent(run) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(add).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clear))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jRadioButton1).addComponent(jRadioButton2) .addComponent( label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ignoreAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ignoreOnce, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) .addContainerGap(245, Short.MAX_VALUE))); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] { jButton1, jButton2, jButton3, jButton4 }); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] { add, clear, run }); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1).addComponent(jButton2) .addComponent(jButton3).addComponent(jButton4))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(instruction) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup().addGap(26, 26, 26) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ignoreAll).addGap(18, 18, 18) .addComponent(ignoreOnce, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(run, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(clear, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(899, 899, 899) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 5, Short.MAX_VALUE) .addGap(482, 482, 482).addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32))); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] { jButton1, jButton2, jButton3, jButton4 }); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] { ignoreAll, ignoreOnce }); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] { add, clear, run }); pack(); }// </editor-fold>//GEN-END:initComponents private void runActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runActionPerformed /*Check words for errors*/ text = textArea.getText(); highlighter = textArea.getHighlighter(); boolean English = jRadioButton1.isSelected(); if (text.length() == 0) { if (English) { instruction.setText("Type or paste text below or Click 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 (English) instruction.setText("No errors detected!"); else instruction.setText("akukho mpazamo zifunyenweyo"); instruction.setForeground(Color.BLUE); return; } else { if (English) instruction.setText("Click spellcheck button to process one error 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; //boolean isiXhosa = jRadioButton3.isSelected(); //boolean isiZulu = jRadioButton4.isSelected(); //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_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"); boolean English = jRadioButton1.isSelected(); try { String[] words; int start = 0; int end = 0; boolean active = true; if (text.length() == 0) { if (English) { instruction.setText("Type or paste text below or Click Open file to load a file!"); } else { instruction.setText("cofa iqhosha lokuvula ifayile ukuze ubonise ifayile"); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (English) { instruction.setText("Click Spellcheck first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (pos >= text.length()) { if (English) instruction .setText("You reached the end of your text. Click the spellcheck button to start over"); 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 (English) 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 /*Adds flagged words into a user dictionary*/ text = textArea.getText(); highlighter = textArea.getHighlighter(); highlighter.removeAllHighlights(); String[] sentences = text.split("\n"); //boolean English = jRadioButton1.isSelected(); try { String[] words; int start = 0; int end = 0;//sentences.length; boolean active = true; if (text.length() == 0) { if (language) { instruction.setText("Type or paste text below or Click Open file to load a file!"); } else { instruction.setText( "bhala okanye beka umbhalo ngezantsi) okanye (cofa iqhosha lokuvula ifayile ukuze ubonise ifayile"); } 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 spellcheck 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"); boolean English = jRadioButton1.isSelected(); try { String[] words; int start = 0; int end = 0; boolean active = true; if (text.length() == 0) { if (English) { instruction.setText("Type or paste text below or Click Open file to load a file!"); } else { instruction.setText("cofa iqhosha lokuvula ifayile ukuze ubonise ifayile"); } instruction.setForeground(Color.red); return; } else if (!highlightSet) { if (English) { instruction.setText("Click Run first!"); } else { instruction.setText("Cofa uSebenzisa kuqala!"); } instruction.setForeground(Color.red); return; } else if (pos >= text.length()) { if (English) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText( "Ufike esiphelweni sombhalo wakho. Cofa iqhosha lokujonga upelo ukuqalela kakutsha"); 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); } // boolean English = jRadioButton1.isSelected(); if (pos >= text.length() && sentNo >= sentences.length) { if (English) instruction.setText("You reached the end of your text. Click run to check again"); else instruction.setText( "Ufike esiphelweni sombhalo wakho. Cofa iqhosha lokujonga upelo ukuqalela kakutsha"); instruction.setForeground(Color.BLUE); currentWord = ""; return; } highlightSet = true; }//GEN-LAST:event_addActionPerformed private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed // Add user dictionary to the dictionary 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 boolean English = jRadioButton1.isSelected(); if (textArea.getText().length() == 0) { if (English) instruction.setText("Nothing to clear"); else instruction.setText("Akukho okucishwayo"); instruction.setForeground(Color.red); } else { if (English) 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 textAreaAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_textAreaAncestorResized // TODO add your handling code here: }//GEN-LAST:event_textAreaAncestorResized private void textAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textAreaKeyTyped // TODO add your handling code here: boolean English = jRadioButton1.isSelected(); int len = textArea.getText().length(); if (highlightSet && len != 0) { if (English) { instruction.setText("Spellcheck to check changes or to continue to next error"); } else { instruction.setText("Khangela upelo kwezinguquko ozenzile noma udlulele ephutheni elilandelayo "); } instruction.setForeground(Color.blue); highlighter.removeAllHighlights(); highlightSet = false; } else if (len == 0) { if (English) { instruction.setText("Type or paste text below or Click 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 (English) { instruction.setText("Spellcheck to check for errors"); } else { instruction.setText("Cofa iSpellcheck ukuze ukhangele upelo"); } instruction.setForeground(Color.blue); } }//GEN-LAST:event_textAreaKeyTyped private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // Open file from machine int returnVal = fileChooser.showOpenDialog(this); boolean English = jRadioButton1.isSelected(); if (English) instruction.setText("Spellcheck 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_jButton1ActionPerformed private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: boolean English = jRadioButton1.isSelected(); if (English) { jButton1.setText("Open file"); jButton2.setText("Save file"); jButton3.setText("Help"); jButton4.setText("Exit"); // jLabel1.setText("*Hover over buttons to view tool tips or click help for instructions"); //hover over ignoreAll.setText("Ignore All"); ignoreOnce.setText("Ignore Once"); label1.setText("Interface language"); //jLabel3.setText("Perform error detection for:"); //tooltip texts jButton1.setToolTipText("Open file"); jButton2.setToolTipText("Save file to machine"); jButton3.setToolTipText("Open help menu"); jButton4.setToolTipText("Close application"); ignoreAll.setToolTipText("Ignore all errors"); ignoreOnce.setToolTipText("Ignore error once"); run.setToolTipText("Check spelling errors"); clear.setToolTipText("Clear textbox"); add.setToolTipText("Add word to dictionary"); } }//GEN-LAST:event_jRadioButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // Save file being edited to machine int len = textArea.getText().length(); boolean English = jRadioButton1.isSelected(); if (len == 0) { if (English) { instruction.setText("You are trying to save an empty file!"); instruction.setForeground(Color.RED); } else { instruction.setText("Uzama ukugcina ifayile engenanto!"); instruction.setForeground(Color.RED); } //System.out.println(data); } else { 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_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // User instructions boolean English = jRadioButton1.isSelected(); try { if (English) { InputStream ins = IsiXhosa_Spellchecker.class.getResourceAsStream("resources/Instructions.txt"); BufferedReader insReader = new BufferedReader(new InputStreamReader(ins)); textarea.read(insReader, ins); helpWindow.setVisible(true); } else { InputStream ins = IsiXhosa_Spellchecker.class .getResourceAsStream("resources/XhosaInstructions.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_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // Exit button handler and saves to dictionary updates the trigrams aswell System.exit(0); }//GEN-LAST:event_jButton4ActionPerformed private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed // TODO add your handling code here: boolean isXhosa = jRadioButton2.isSelected(); if (isXhosa) { jButton1.setText("Vula ifayile"); jButton2.setText("Gcona ifayile"); jButton3.setText("Uncedo"); jButton4.setText("Phuma"); ignoreAll.setText("Ugahoyi konke"); ignoreOnce.setText("Ungahoyi inye"); label1.setText("Ulwimi loxwebhu"); //jLabel3.setText("Khangela imiphosiso ye:"); // jLabel1.setText(""); //hover over //tooltip texts jButton1.setToolTipText("Vula ifayile"); jButton2.setToolTipText("Gcona ifayile"); jButton3.setToolTipText("Thola Uncedo"); jButton4.setToolTipText("Phuma"); run.setToolTipText("jonga impazamo yokupela kwa magama"); clear.setToolTipText("Cima amagama"); add.setToolTipText("Faka eligama kwi dikshinari"); ignoreAll.setToolTipText("Susihoya isiphene"); ignoreOnce.setToolTipText("uzihoya zonke iziphene"); // jLabel1.setToolTipText(""); //hover over } else { } }//GEN-LAST:event_jRadioButton2ActionPerformed /* * Checks for all errors */ private boolean noErrors() { String[] sentences = textArea.getText().split("\n"); String[] words; int sentence = 0; /*Check for zulu errors begin*/ 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; /**Check for zulu errors end*/ } 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.JButton add; private javax.swing.JButton clear; private javax.swing.JButton close; private javax.swing.JFileChooser fileChooser; private javax.swing.JButton ignoreAll; private javax.swing.JButton ignoreOnce; private javax.swing.JLabel instruction; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private java.awt.Label label1; private javax.swing.JPopupMenu popup; private javax.swing.JButton run; private javax.swing.JTextArea textArea; // End of variables declaration//GEN-END:variables private javax.swing.JFrame helpWindow; private JPanel mainPanel; private JTextArea textarea; }