Thursday, February 14, 2013

JMenuBar: a Tutorial



It's easy to use JMenuBar in your JFrame. These are the simple steps to use JMenubar:

1. Copy the setMenuBar() method below

2. Paste the method in your class that extends JFrame

3. Configure the method on your own

4. Add a line "setMenuBar();" at the bottom of the constructor of your JFrame class



The following is an example of using JMenuBar. Just copy the setMenuBar() method and configure it on your own.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
 
public class MyJFrame extends JFrame {
 
    private JPanel contentPane;
 
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyJFrame frame = new MyJFrame();
                    frame.setTitle("JmenuBar example");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
     
    /**
     * Create the frame.
     */
    public MyJFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
         
        setMenuBar();    //set JMenubar
    }
 
 
    private void setMenuBar(){
         
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(Color.lightGray);
         
        //////////////////// File
        JMenu fileMenu = new JMenu("File");
        JMenuItem openMenuItem = new JMenuItem("Open File");
        openMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                 
            }
        });
        fileMenu.add(openMenuItem);
 
        JMenuItem saverf5xAndMenuItem = new JMenuItem("Save");
        fileMenu.add(saverf5xAndMenuItem);
 
        JMenuItem exitMenuItem = new JMenuItem("Exit");
        exitMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
             
            }
        });
        fileMenu.add(exitMenuItem);
        menuBar.add(fileMenu);
 
        ////////////////////Edit
        JMenu editMenu = new JMenu("Edit");
        JMenuItem copyMenuItem = new JMenuItem("ergedgvdfergv");
        copyMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
             
            }
        });
        editMenu.add(copyMenuItem);
 
        JMenuItem copyOriginalrf5xMenuItem = new JMenuItem("SFdfsrfs");
        copyOriginalrf5xMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                 
            }
        });
        editMenu.add(copyOriginalrf5xMenuItem);
 
        JMenuItem clearMenuItem = new JMenuItem("sferfgedrg");
        clearMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
 
            }
        });
        editMenu.add(clearMenuItem);
 
        JMenuItem clearrf5xMenuItem = new JMenuItem("egdfgvd");
        clearrf5xMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
            }
        });
        editMenu.add(clearrf5xMenuItem);
 
        JMenuItem clearBothMenuItem = new JMenuItem("rthfghrth");
        clearBothMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
             
            }
        });
        editMenu.add(clearBothMenuItem);
        menuBar.add(editMenu);
 
         
        ////////////////////Help
         
        JMenu helpMenu = new JMenu("Help");
        JMenuItem aboutrf5xMenuItem = new JMenuItem("About");
        aboutrf5xMenuItem.addActionListener(new ActionListener() {
             
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                 
            }
        });
        helpMenu.add(aboutrf5xMenuItem);
        menuBar.add(helpMenu);
         
        this.setJMenuBar(menuBar);
    }
     
}




Tuesday, February 12, 2013

Tutorial on Jazzy Spell Checker


Jazzy is a useful Java Open Source Spell Checker. This post is a tutorial on how to use it:

1.Download jazzy-core-0.5.2.jar from
 http://repo1.maven.org/maven2/net/sf/jazzy/jazzy-core/0.5.2/jazzy-core-0.5.2.jar and add it as a library to your project.


2. Create a folder with a dictionary.txt text file. The text file contains a list of English words, such as http://www.cs.princeton.edu/introcs/data/words.utf-8.txt or any other good word lists.






3. Copy the codes below with which to create JazzySpellChecker.java in a package in the project. Configure it on your own, and use the spell checker to tackle spelling errors.

package test;
package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



import com.swabunga.spell.engine.SpellDictionaryHashMap;
import com.swabunga.spell.engine.Word;
import com.swabunga.spell.event.SpellCheckEvent;
import com.swabunga.spell.event.SpellCheckListener;
import com.swabunga.spell.event.SpellChecker;
import com.swabunga.spell.event.StringWordTokenizer;
import com.swabunga.spell.event.TeXWordFinder;

public class JazzySpellChecker implements SpellCheckListener {
 
 private SpellChecker spellChecker;
 private List misspelledWords;
 
 /**
  * get a list of misspelled words from the text
  * @param text
  */
 public List getMisspelledWords(String text) {
  StringWordTokenizer texTok = new StringWordTokenizer(text,
    new TeXWordFinder());
  spellChecker.checkSpelling(texTok);
  return misspelledWords;
 }
 
 private static SpellDictionaryHashMap dictionaryHashMap;
 
 static{
 
  File dict = new File("dictionary/dictionary.txt");
  try {
   dictionaryHashMap = new SpellDictionaryHashMap(dict);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 private void initialize(){
   spellChecker = new SpellChecker(dictionaryHashMap);
   spellChecker.addSpellCheckListener(this);  
 }
 
 
 public JazzySpellChecker() {
  
  misspelledWords = new ArrayList();
  initialize();
 }

 /**
  * correct the misspelled words in the input string and return the result
  */
 public String getCorrectedLine(String line){
  List misSpelledWords = getMisspelledWords(line);
  
  for (String misSpelledWord : misSpelledWords){
   List suggestions = getSuggestions(misSpelledWord);
   if (suggestions.size() == 0)
    continue;
   String bestSuggestion = suggestions.get(0);
   line = line.replace(misSpelledWord, bestSuggestion);
  }
  return line;
 }
 
 public String getCorrectedText(String line){
  StringBuilder builder = new StringBuilder();
  String[] tempWords = line.split(" ");
  for (String tempWord : tempWords){
   if (!spellChecker.isCorrect(tempWord)){
    List suggestions = spellChecker.getSuggestions(tempWord, 0);
    if (suggestions.size() > 0){
     builder.append(spellChecker.getSuggestions(tempWord, 0).get(0).toString());
    }
    else
     builder.append(tempWord);
   }
   else {
    builder.append(tempWord);
   }
   builder.append(" ");
  }
  return builder.toString().trim();
 }
 
 
 public List getSuggestions(String misspelledWord){
  
  @SuppressWarnings("unchecked")
  List su99esti0ns = spellChecker.getSuggestions(misspelledWord, 0);
  List suggestions = new ArrayList();
  for (Word suggestion : su99esti0ns){
   suggestions.add(suggestion.getWord());
  }
  
  return suggestions;
 }

 
 @Override
 public void spellingError(SpellCheckEvent event) {
  event.ignoreWord(true);
  misspelledWords.add(event.getInvalidWord());
 }

 public static void main(String[] args) {
  JazzySpellChecker jazzySpellChecker = new JazzySpellChecker();
  String line = jazzySpellChecker.getCorrectedLine("This is a boook");
  System.out.println(line);
 }
}


PS:
1.The "string ... string" above is caused by a bug of the syntax highlighter and can be ignored.
2. I found a bug and corrected the code on April 10th.

Sunday, December 16, 2012

An effective solution to "java.sql.SQLException: [SQLITE_BUSY] The database file is locked (database is locked)"

Similar to links like:

http://stackoverflow.com/questions/7930139/android-database-locked
http://stackoverflow.com/questions/13891006/getting-sqlite-busy-database-file-is-locked-with-select-statements

The sqlite database is sometimes locked very long when trying to insert, delete or update data with a java program. I had read the posts above but found no definite and clear solution in these  answers. I had also tried the proposed solution shown in the video https://www.youtube.com/watch?v=o7dn0cLvb5o about "the database is locked problem" in vain.


But finally, I figured out a simple and effective way to circumvent this problem so that I can continue my coding. The solution is as follows:


1.Backup the database folder where the locked sqlite db is located.





 2. Use Unlocker to delete the locked .db file




Unlocker can be downloaded from 
http://www.emptyloop.com/unlocker/Unlocker1.9.1-x64.exe
in the webpage
http://www.emptyloop.com/unlocker/

3.Copy the backup .db file back to the directory of the deleted locked sqlite .db.



These three simple steps can effectively solve the problem of  "java.sql.SQLException: [SQLITE_BUSY]  The database file is locked (database is locked)." Try it to evade this problem if baffled by it for quite a long time.


Saturday, November 24, 2012

Way to solve "could not create audio stream from input stream"


Similar to this link,

http://www.javaprogrammingforums.com/whats-wrong-my-code/9116-could-not-create-audio-stream-input-stream.html

I was also once confronted with the problem of "could not create audio stream from input stream"
"Exception in thread "main" java.io.IOException: could not create audio stream from input stream"
when trying to use TTS api of some website and playing the recorded .wav file.

After searching on the Internet for quite much time, I ultimately found out the way to solve this problem, which is as follows:

1.Download jl1.0.jar, jmf.jar, and mp3plugin.jar.

2.Copy the jar files to a folder like lib inside the java project.

3.Go to Configure Build Path→Libraries→Add Jars to add these jars.


With these steps, the problem is solved.


The reason behind this IOException is probably related to the file format. A .wav file may be encoded with an mp3 codec.