言葉勉強用ツール 2.0

//add function that if you double click then search the word by google
package jp.co.learn.dict;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

public class LearnWords extends JFrame implements ActionListener, KeyListener, Runnable {

	static final long serialVersionUID = 1L;
	static LearnWords frame;
	JLabel label;
	int sec;
	JPopupMenu menubar = new JPopupMenu();
	static List<String> wordList = new ArrayList<String>();
	String filename = "";
	MouseEvent start;
	int intTime = 1000;
	int intRight = 40;
	int intDown = 20;
	int CONTENT_LABEL_HEIGHT = 25;
	String MODE_AUTO = "AUTO";
	Properties properties;

	public static void main(String[] args) throws Exception {

		System.setProperty("awt.useSystemAAFontSettings", "on");
		System.setProperty("swing.aatext", "true");
		try {
			// 系统风格
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 下面使用全局字体设置
		initGlobalFontSetting(new Font("メイリオ", 0, 12));

		frame = new LearnWords();
		

	}

	public LearnWords() {
		addKeyListener(this);
		sec = 0;

		JMenu menu1 = new JMenu("文件");
		JMenu menu2 = new JMenu("随機");
		JMenu menu3 = new JMenu("時間");
		JMenu menu4 = new JMenu("日本語言葉");
		JMenu menu5 = new JMenu("関閉");
		JMenu menu6 = new JMenu("help");

		menubar.add(menu1);
		menubar.add(menu2);
		menubar.add(menu3);
		menubar.add(menu4);
		menubar.add(menu5);
		menubar.add(menu6);

		JMenuItem menuitem1_2 = new JMenuItem("開く");

		JMenuItem menuitem2_1 = new JMenuItem("随機開始");
		JMenuItem menuitem2_2 = new JMenuItem("随機終了");

		JMenuItem menuitem3_1 = new JMenuItem("時間+");
		JMenuItem menuitem3_2 = new JMenuItem("時間-");

		JMenuItem menuitem4_1 = new JMenuItem("日本語能力試験出題基準語彙表-N1");
		JMenuItem menuitem4_2 = new JMenuItem("日本語能力試験出題基準語彙表-N2");
		JMenuItem menuitem4_3 = new JMenuItem("日本語能力試験出題基準語彙表-N3");
		JMenuItem menuitem4_4 = new JMenuItem("日本語能力試験出題基準語彙表-N4");
		JMenuItem menuitem4_5 = new JMenuItem("みんなの日本語の単語");
		JMenuItem menuitem4_6 = new JMenuItem("日本語能力試験出題基準カタカナ語語彙表");

		JMenuItem menuitem5_1 = new JMenuItem("exit");

		JMenuItem menuitem6_1 = new JMenuItem("+キー：頻度1秒追加");
		JMenuItem menuitem6_2 = new JMenuItem("-キー：頻度1秒減少");
		JMenuItem menuitem6_3 = new JMenuItem("スペースキー:随機開始");
		JMenuItem menuitem6_4 = new JMenuItem("CTRLキー:随機終了");
		JMenuItem menuitem6_5 = new JMenuItem("ESCキー：exit");

		menu1.add(menuitem1_2);
		menu2.add(menuitem2_1);
		menu2.add(menuitem2_2);
		menu3.add(menuitem3_1);
		menu3.add(menuitem3_2);
		menu4.add(menuitem4_1);
		menu4.add(menuitem4_2);
		menu4.add(menuitem4_3);
		menu4.add(menuitem4_4);
		menu4.add(menuitem4_5);
		menu4.add(menuitem4_6);
		menu5.add(menuitem5_1);
		menu6.add(menuitem6_1);
		menu6.add(menuitem6_2);
		menu6.add(menuitem6_3);
		menu6.add(menuitem6_4);
		menu6.add(menuitem6_5);

		menuitem1_2.addActionListener(this);
		menuitem1_2.setActionCommand("Open");

		menuitem2_1.addActionListener(this);
		menuitem2_1.setActionCommand("ランダム開始");
		menuitem2_2.addActionListener(this);
		menuitem2_2.setActionCommand("ランダム終了");

		menuitem3_1.addActionListener(this);
		menuitem3_1.setActionCommand("addTime");
		menuitem3_2.addActionListener(this);
		menuitem3_2.setActionCommand("decreaseTime");

		menuitem4_1.addActionListener(this);
		menuitem4_1.setActionCommand("readJapaneseN1");
		menuitem4_2.addActionListener(this);
		menuitem4_2.setActionCommand("readJapaneseN2");
		menuitem4_3.addActionListener(this);
		menuitem4_3.setActionCommand("readJapaneseN3");
		menuitem4_4.addActionListener(this);
		menuitem4_4.setActionCommand("readJapaneseN4");
		menuitem4_5.addActionListener(this);
		menuitem4_5.setActionCommand("readJapaneseMinnna");
		menuitem4_6.addActionListener(this);
		menuitem4_6.setActionCommand("readJapaneseKana");

		menuitem5_1.addActionListener(this);
		menuitem5_1.setActionCommand("exit");

		JPanel p = new JPanel();
		label = new JLabel();
		label.setBackground(Color.gray);
		label.setVerticalAlignment(JLabel.CENTER);
		label.setText("Loading......");
		p.add(label);

		Container contentPane = getContentPane();
		contentPane.add(p, BorderLayout.LINE_START);

		WindowDrugMove mouseListener = new WindowDrugMove();
		// マウスを最初に掴んだ時
		label.addMouseListener(mouseListener);
		// マウスをドラッグした時
		label.addMouseMotionListener(mouseListener);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(intRight, intDown, 400, CONTENT_LABEL_HEIGHT);
		setAlwaysOnTop(true);
		setUndecorated(true);
		setBackground(new Color(0x0, true));
		setVisible(true);

		// プロパティファイルを読み込む。
		properties = new Properties();
		try {
			String currentPath = new File(".").getAbsoluteFile().getParent();
			File settingFile = new File(currentPath + "\\LearnWords.ini");
			if (!settingFile.exists()) {
				properties.setProperty("MODE", MODE_AUTO);
				properties.setProperty("DICT", "jp.co.learn.dict.JapaneseN1");
				properties.store(new FileOutputStream(settingFile), "Comments");
			} else {
				properties.load(new FileInputStream(settingFile));
			}
		} catch (Exception e) {
		}

		filename = "C:\\en.txt";
		readFile(filename);

		
		Thread thread = new Thread(this);
		thread.start();
	}
	
	
	

	/**
	 * 鼠标拖动
	 *
	 * @author Administrator
	 *
	 */
	class WindowDrugMove implements MouseMotionListener, MouseListener {
		private Point loc;

		public void mouseMoved(MouseEvent e) {
		}

		public void mouseDragged(MouseEvent e) {
			Window window = frame;
			loc = window.getLocation(loc);
			int x = loc.x - start.getX() + e.getX();
			int y = loc.y - start.getY() + e.getY();
			window.setLocation(x, y);
		}

		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {
				
		         try {
		        	 
//		        	 String jisUni = new String(wordList.get(sec).getBytes("Shift_JIS"),"Shift_JIS"); 
//		        	//EUCとしてのユニコード 
//		        	String eucjpUni = new String(jisUni.getBytes("UTF-8"),"UTF-8");
//		        	 Process p =Runtime.getRuntime().exec("H:\\iexplore.exe http://www.google.com/search?q="+wordList.get(sec)+"&ie=euc-jp" + "&hl=ja");
		        	 
		        	 Process p =Runtime.getRuntime().exec("H:\\Chrome\\Application\\chrome.exe http://www.google.com/search?q="+wordList.get(sec-1)+"&ie=euc-jp" + "&hl=ja");
					
					 try {
						p.waitFor();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				        InputStream input = p.getInputStream();
				        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
				            String lines = "";
				            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
				                lines += line + "\n";
				            }
				            System.out.println(lines);
				        }
				        
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                }
		}

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
			start = e;
			showPopup(e);
		}

		public void mouseReleased(MouseEvent e) {
			// 右键菜单
			showPopup(e);
		}
	}

	public void actionPerformed(ActionEvent e) {

		if (e.getActionCommand() == "Open") {
			JFileChooser jfc1 = new JFileChooser();
			// 名前設定
			jfc1.setDialogTitle("ファイルを選択してください。");
			// ディフォルトほうしき
			jfc1.showOpenDialog(null);
			jfc1.setVisible(true);
			// 全パス取得
			filename = jfc1.getSelectedFile().getAbsolutePath();
			readFile(filename);
		} else if (e.getActionCommand() == "ランダム開始") {
			label.setText("<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1' color='green'>ランダム開始...</font></html>");
			Collections.shuffle(wordList);
			return;
		} else if (e.getActionCommand() == "ランダム終了") {
			label.setText("<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1' color='green'>ランダム終了...</font></html>");
			reRadom();
			return;
		} else if (e.getActionCommand() == "addTime") {
			if (intTime >= 1000) {
				intTime = intTime + 1000;
			} else if (250 <= intTime && intTime < 1000) {
				intTime = intTime * 2;
			}
		} else if (e.getActionCommand() == "decreaseTime") {
			if (intTime > 1000) {
				intTime = intTime - 1000;
			} else if (intTime >= 500) {
				intTime = intTime / 2;
			}
		} else if (e.getActionCommand() == "readJapaneseN1") {
			loadDict("jp.co.learn.dict.JapaneseN1");
			sec = 0;
		} else if (e.getActionCommand() == "readJapaneseN2") {
			loadDict("jp.co.learn.dict.JapaneseN2");
			sec = 0;
		}

		outPutMsgOfchangTime();
		//
		// else if (e.getActionCommand() == "readJapaneseN3") {
		// readJapaneseN3();
		// sec = 0;
		// } else if (e.getActionCommand() == "readJapaneseN4") {
		// readJapaneseN4();
		// sec = 0;
		// } else if (e.getActionCommand() == "readJapaneseMinnna") {
		// readJapaneseMinnna();
		// sec = 0;
		// } else if (e.getActionCommand() == "readJapaneseKana") {
		// readJapaneseKana();
		// sec = 0;
		// }

		if ("exit".equals(e.getActionCommand())) {
			int dialogButton = JOptionPane.YES_NO_OPTION;
			if (dialogButton == JOptionPane.YES_OPTION) {
				writeFile();
				System.exit(NORMAL);
			}
		}

		menubar.setVisible(false);
		frame.setBounds(frame.getX(), frame.getY(), frame.getWidth(), CONTENT_LABEL_HEIGHT);
	}

	public void run() {
		do {
			if (sec + 1 > wordList.size()) {
				sec = 0;
			} else {
				label.setText("<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1'>" + wordList.get(sec).trim() + "</font></html>");
				sec++;
				if (sec == wordList.size()) {
					sec = 0;
				}
			}
			try {
				Thread.sleep(intTime);
			} catch (InterruptedException e) {
			}
		} while (true);
	}

	/**
	 * read file 指定されたTXTファイルを読む
	 *
	 * @return なし
	 */
	public void readFile(String fileName) {

		wordList = new ArrayList<String>();
		sec = 0;
		try {
			Files.lines(Paths.get(fileName)).forEachOrdered(s -> {
				if (null != s && s.trim().length() > 1 && !s.contains("OK")) {
					wordList.add(s);
				}
			});
			menubar.setVisible(false);
			if (wordList.size() == 0) {
				loadDict("jp.co.learn.dict.JapaneseN1");
			}
		} catch (IOException e1) {
			if (wordList.size() == 0) {
				loadDict("jp.co.learn.dict.JapaneseN1");
				sec = 0;
			}
			e1.printStackTrace();
		}
	}

	/**
	 * 键盘监听
	 */
	@Override
	public void keyPressed(KeyEvent e) {

		// + KEY 繰り返す時間追加
		if (e.getKeyCode() == 107) {
			if (intTime >= 1000) {
				intTime = intTime + 1000;
			} else if (250 <= intTime && intTime < 1000) {
				intTime = intTime * 2;
			}
		}
		// - KEY 繰り返す時間減少
		else if (e.getKeyCode() == 109) {
			if (intTime > 1000) {
				intTime = intTime - 1000;
			} else if (intTime >= 500) {

				intTime = intTime / 2;
			}

		}

		// ESCキー 終了
		else if (e.getKeyCode() == 27) {
			writeFile();
			System.exit(NORMAL);
		}
		// SPACE ランダム開始
		else if (e.getKeyCode() == 32) {
			Collections.shuffle(wordList);
		}
		// CTRL ランダム終了
		else if (e.getKeyCode() == 17) {
			label.setText("ランダム終了");
			reRadom();
		}
		// ENTER わかる言葉を表記する。次回表示しない
		else if (e.getKeyCode() == 10) {
			if (wordList.get(sec - 1) == label.getText()) {
				wordList.remove(sec - 1);
				wordList.add(sec - 1, "OK " + label.getText());
				System.out.println("OK");
			} else {
				System.out.println("NG");
			}
		}
		// 右 下一个单词
		else if (e.getKeyCode() == 39) {
			sec++;
			if (sec == wordList.size()) {
				sec = 0;
			}
			label.setText(
					"<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1'>" + wordList.get(sec).trim() + "</font></html>");
		}
		// 下 向下移动
		else if (e.getKeyCode() == 40) {
			intDown = intDown + 50;
			frame.setBounds(frame.getX(), intDown, frame.getWidth(), CONTENT_LABEL_HEIGHT);
		}
		// 上 向上移动
		else if (e.getKeyCode() == 38) {
			intDown = intDown - 50;
			if (intDown > 0) {
				frame.setBounds(frame.getX(), intDown, frame.getWidth(), CONTENT_LABEL_HEIGHT);
			}
		}
		// 左 上一个单词
		else if (e.getKeyCode() == 37) {
			sec--;
			if (sec < 0) {
				sec = 0;
			}
			label.setText(
					"<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1'>" + wordList.get(sec).trim() + "</font></html>");
		}
		
		outPutMsgOfchangTime();
	}

	private void outPutMsgOfchangTime() {
		if (intTime<1000) {
			String text = String.valueOf(intTime) + "ミリ秒に変更しました。";
			label.setText("<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1' color='green'>" + text + "</font></html>");
		}else{
			String text = String.valueOf(intTime / 1000) + "秒に変更しました。";
			label.setText("<html><font face='ＭＳ 明朝,SimSun,宋体' size='+1' color='green'>" + text + "</font></html>");	
		}
	}

	/**
	 * ランダム解除 ランダムを解除する。
	 */
	private void reRadom() {
		Collections.sort(wordList, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
	}

	/**
	 * ファイル更新。 分かる言葉この行目の前にOKを追記する。
	 */
	public void writeFile() {

		FileSystem fs = FileSystems.getDefault();

		/* ファイルの書き込み */
		Path outputPath = fs.getPath(filename);
		try (BufferedWriter bw = Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8,
				StandardOpenOption.CREATE)) {
			wordList.forEach(s -> {
				try {
					bw.write(s + "\r\n");
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private void loadDict(String param) {
		try {
			wordList.clear();
			Class<?> clazz = Class.forName(param);
			Object obj = clazz.newInstance();
			Method method = clazz.getMethod("read");
			wordList = (List<String>) method.invoke(obj);
		} catch (Exception e) {
		}
	}

	private void showPopup(MouseEvent e) {
		if (e.isPopupTrigger()) {
			menubar.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	public static void initGlobalFontSetting(Font fnt) {
		FontUIResource fontRes = new FontUIResource(fnt);
		for (Enumeration keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
			Object key = keys.nextElement();
			Object value = UIManager.get(key);
			if (value instanceof FontUIResource)
				UIManager.put(key, fontRes);
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
	}

	
	
	public static boolean isUTF8(byte[] src)
    {
        try {
            byte[] tmp = new String(src, "UTF8").getBytes("UTF8");
            return Arrays.equals(tmp, src);
        }
        catch(UnsupportedEncodingException e) {
            return false;
        }
    }

    public static boolean isSJIS(byte[] src)
    {
        try {
            byte[] tmp = new String(src, "Shift_JIS").getBytes("Shift_JIS");
            return Arrays.equals(tmp, src);
        }
        catch(UnsupportedEncodingException e) {
            return false;
        }
    }

}