jp.massbank.spectrumsearch.SearchPage.java Source code

Java tutorial

Introduction

Here is the source code for jp.massbank.spectrumsearch.SearchPage.java

Source

/*
 * Copyright (C) 2008 JST-BIRD MassBank
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

package jp.massbank.spectrumsearch;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import jp.massbank.spectrumsearch.accessor.DbAccessor;
import jp.massbank.spectrumsearch.entity.constant.Constant;
import jp.massbank.spectrumsearch.entity.constant.SystemProperties;
import jp.massbank.spectrumsearch.entity.db.Compound;
import jp.massbank.spectrumsearch.entity.gui.GuiDbTableRow;
import jp.massbank.spectrumsearch.entity.gui.GuiResultTableRow;
import jp.massbank.spectrumsearch.entity.param.SearchQueryParam;
import jp.massbank.spectrumsearch.entity.type.IonMode;
import jp.massbank.spectrumsearch.entity.type.ToleranceUnit;
import jp.massbank.spectrumsearch.gui.AbstractDialog;
import jp.massbank.spectrumsearch.gui.MenuBarGenerator;
import jp.massbank.spectrumsearch.gui.ProgressDialog;
import jp.massbank.spectrumsearch.logic.CompoundLogic;
import jp.massbank.spectrumsearch.logic.SpectrumLogic;
import jp.massbank.spectrumsearch.logic.search.SearchLogic;
import jp.massbank.spectrumsearch.model.PackageRecData;
import jp.massbank.spectrumsearch.model.PackageSpecData;
import jp.massbank.spectrumsearch.model.PeakData;
import jp.massbank.spectrumsearch.model.UserFileData;
import jp.massbank.spectrumsearch.util.CommonUtil;
import jp.massbank.spectrumsearch.util.MassBankDirSyncThread;
import jp.massbank.spectrumsearch.util.SiteUtil;
import massbank.GetInstInfo;
import massbank.MassBankCommon;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * Start point of this application.
 */
public class SearchPage extends JFrame {

    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = Logger.getLogger(SearchPage.class);

    private static final String APPLICATION_TITLE = "Spectrum Search | massbank.jp";

    public static void main(String[] args) {
        LOGGER.info("Application start!");
        LOGGER.info("Spectrum Search version " + SearchPage.class.getPackage().getImplementationVersion());

        SearchPage appli = new SearchPage();
        appli.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        appli.setTitle(APPLICATION_TITLE);
        appli.setSize(1200, 700);

        try {
            appli.init();
            appli.setVisible(true);
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    }

    // TODO this will be removed. 
    //   static String baseUrl = "http://www.massbank.jp/";

    private GetInstInfo instInfo = null;

    private static int PRECURSOR = -1;
    private static float TOLERANCE;
    public static int CUTOFF_THRESHOLD;
    private static final int LEFT_PANEL_WIDTH = 430;

    private static final int TAB_ORDER_DB = 0;
    static final int TAB_ORDER_FILE = 1;
    private static final int TAB_RESULT_DB = 0;
    private static final int TAB_VIEW_COMPARE = 0;
    private static final int TAB_VIEW_PACKAGE = 1;

    private static final String BTN_LABEL_RECORD_SEARCH_BY_NAME = "Search Name";
    private static final String BTN_LABEL_RECORD_SEARCH_ALL = "All";
    private static final String BTN_LABEL_SEARCH_PARAM_SETTING = "Search Parameter Setting";

    public static final String COL_LABEL_NAME = "Name";
    public static final String COL_LABEL_SCORE = "Score";
    public static final String COL_LABEL_HIT = "Hit";
    public static final String COL_LABEL_ID = "ID";
    public static final String COL_LABEL_ION = "Ion";
    public static final String COL_LABEL_CONTRIBUTOR = "Contributor";
    public static final String COL_LABEL_NO = "No.";
    public static final String COL_LABEL_ORDER = "Order";
    public static final String COL_LABEL_TYPE = "Type";
    public static final String COL_LABEL_MATCH = "Match";
    public static final String COL_LABEL_DISABLE = "Disable";
    public static final String COL_LABEL_PEAK = "Peak";
    public static final String COL_LABEL_PRECURSOR = "Precursor";

    UserFileData[] userDataList = null;

    public static final String TABLE_QUERY_FILE = "QueryFile";
    public static final String TABLE_QUERY_DB = "QueryDb";
    public static final String TABLE_RESULT = "Result";

    TableSorter fileSorter = null; // 
    private TableSorter querySorter = null; // DB
    private TableSorter resultSorter = null; // ?

    private JTable queryFileTable = null; // 
    private JTable queryDbTable = null; // DB
    private JTable resultTable = null; // ?

    private PeakPanel queryPlot = new PeakPanel(false); // ?
    private PeakPanel resultPlot = new PeakPanel(false); // ??
    private PeakPanel compPlot = new PeakPanel(true); // ?

    JTabbedPane queryTabPane = new JTabbedPane(); // 
    private JTabbedPane resultTabPane = new JTabbedPane(); // ?
    private JTabbedPane viewTabPane = new JTabbedPane(); // 

    private JScrollPane queryFilePane = null; // 
    private JScrollPane resultPane = null; // DB
    private JScrollPane queryDbPane = null; // ?

    private JButton btnName = new JButton(BTN_LABEL_RECORD_SEARCH_BY_NAME);
    private JButton btnAll = new JButton(BTN_LABEL_RECORD_SEARCH_ALL);

    private String saveSearchName = StringUtils.EMPTY;

    private JButton etcPropertyButton = new JButton(BTN_LABEL_SEARCH_PARAM_SETTING);

    private boolean isRecActu; // ()
    private boolean isRecInteg; // (?)
    private boolean isDispSelected; // Package View(?)
    private boolean isDispRelated; // Package View()

    private JRadioButton tolUnit1 = new JRadioButton("unit", true);
    private JRadioButton tolUnit2 = new JRadioButton("ppm");

    private Map<String, List<String>> instGroup; // 
    private LinkedHashMap<String, JCheckBox> instCheck; // ??
    private HashMap<String, Boolean> isInstCheck; // ??
    private LinkedHashMap<String, JCheckBox> msCheck; // MS??
    private HashMap<String, Boolean> isMsCheck; // MS??
    private LinkedHashMap<String, JRadioButton> ionRadio; // ?
    private HashMap<String, Boolean> isIonRadio; // ?

    private boolean isSubWindow = false;

    private JLabel hitLabel = new JLabel(" ");

    //   private ArrayList<String[]> nameList = new ArrayList<String[]>();

    //   private ArrayList nameListAll = new ArrayList();

    //   private String[] siteList ;

    //   public static String[] siteNameList = new String[]{"Keio Univ."};

    private Map<String, GuiDbTableRow> guiDbTableRowMap;

    private JPanel parentPanel2 = null;

    private PackageViewPanel pkgView = null; // PackageView??

    private MassBankCommon mbcommon = new MassBankCommon();
    private final Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);

    /** sequence number for user query file.*/
    int seaqId = 0;
    /** sequence Compound name for user query file.*/
    int seaqCompound = 0;

    //   public static AppletContext context = null;            // 
    static int initAppletWidth = 0; // ??()
    static int initAppletHight = 0; // ??(?)

    public static final int MAX_DISPLAY_NUM = 30; // Package View?

    //   private CookieManager cm;                     // Cookie Manager
    //   private final String COOKIE_PRE = "PRE";         // CookiePRECURSOR
    //   private final String COOKIE_TOL = "TOL";         // CookieTOLERANCE
    //   private final String COOKIE_CUTOFF = "CUTOFF";    // CookieCOOKIE_CUTOFF
    //   private final String COOKIE_INST = "INST";         // CookieINSTRUMENT
    //   private final String COOKIE_MS = "MS";            // CookieMS
    //   private final String COOKIE_ION = "ION";         // CookieION

    private final JRadioButton dispSelected = new JRadioButton("selected", true);
    private final JRadioButton dispRelated = new JRadioButton("related");
    private final JLabel lbl2 = new JLabel("Package View display mode  : ");

    public ProgressDialog dlg;
    public String[] ps = null;
    public String param = "";

    /**
     * 
     * @throws SQLException 
     */
    public void init() throws SQLException {

        // init variables
        guiDbTableRowMap = new HashMap<String, GuiDbTableRow>();

        // ???
        initAppletWidth = getWidth();
        initAppletHight = getHeight();

        // ???URL?
        // 
        //        String confPath = "http://www.massbank.jp/";
        //        String confPath = getCodeBase().toString();
        //      confPath = confPath.replaceAll("/jsp", "");
        //      GetConfig conf = new GetConfig(confPath);
        //      siteNameList = conf.getSiteName();
        //      baseUrl = conf.getServerUrl();

        //      siteNameList = SiteUtil.getSiteNamesArray();

        // Cookie?
        //      cm = new CookieManager( "SerchApplet", 30, true);

        // Precursor m/z?
        initPreInfo();

        // Tolerance?
        initTolInfo();

        // Cutoff Threshold?
        initCutoffInfo();
        //      LOGGER.info(confPath);
        // ?
        instInfo = new GetInstInfo();
        //      instInfo = new GetInstInfo(confPath);
        initInstInfo();

        // MS?
        initMsInfo();

        // ?
        initIonInfo();

        // ?
        createWindow();

        // 
        this.dlg = new ProgressDialog(this);
        //      this.dlg = new ProgressDialog(getFrame());

        // ?
        //      if (getParameter("file") != null) {
        //         loadFile(getParameter("file"));
        //      }
        //      // ???
        //      else if (getParameter("num") != null) {
        //         DefaultTableModel dm = (DefaultTableModel) querySorter.getTableModel();
        //         dm.setRowCount(0);
        //
        //         int num = Integer.parseInt(getParameter("num"));
        //         for (int i = 0; i < num; i++) {
        //            String pnum = Integer.toString(i + 1);
        //            String id = getParameter("qid" + pnum);
        //            String name = getParameter("name" + pnum);
        //            String site = getParameter("site" + pnum);
        //            String[] idNameSite = new String[] { id, name, site };
        //            nameList.add(idNameSite);
        //
        //            site = siteNameList[Integer.parseInt(site)];
        //            String[] idNameSite2 = new String[] { id, name, site, String.valueOf(i + 1) };
        //            dm.addRow(idNameSite2);
        //         }
        //      }
    }

    /**
     * ??
     */
    public void setAllPlotAreaRange() {
        queryPlot.setIntensityRange(PeakPanel.INTENSITY_MAX);
        compPlot.setIntensityRange(PeakPanel.INTENSITY_MAX);
        resultPlot.setIntensityRange(PeakPanel.INTENSITY_MAX);
        PeakData qPeak = queryPlot.getPeaks(0);
        PeakData rPeak = resultPlot.getPeaks(0);
        if (qPeak == null && rPeak == null)
            return;
        double qMax = 0d;
        double rMax = 0d;
        if (qPeak != null)
            qMax = qPeak.compMaxMzPrecusor(queryPlot.getPrecursor());
        if (rPeak != null)
            rMax = rPeak.compMaxMzPrecusor(resultPlot.getPrecursor());
        if (qMax > rMax) {
            queryPlot.setPeaks(null, -1);
            setAllPlotAreaRange(queryPlot);
        } else {
            resultPlot.setPeaks(null, -1);
            setAllPlotAreaRange(resultPlot);
        }
    }

    /**
     * ??
     * @param panel PeakPanel
     */
    public void setAllPlotAreaRange(PeakPanel panel) {
        if (panel == queryPlot) {
            compPlot.setMass(queryPlot.getMassStart(), queryPlot.getMassRange(), queryPlot.getIntensityRange());
            resultPlot.setMass(queryPlot.getMassStart(), queryPlot.getMassRange(), queryPlot.getIntensityRange());
        } else if (panel == compPlot) {
            queryPlot.setMass(compPlot.getMassStart(), compPlot.getMassRange(), compPlot.getIntensityRange());
            resultPlot.setMass(compPlot.getMassStart(), compPlot.getMassRange(), compPlot.getIntensityRange());
        } else if (panel == resultPlot) {
            queryPlot.setMass(resultPlot.getMassStart(), resultPlot.getMassRange(), resultPlot.getIntensityRange());
            compPlot.setMass(resultPlot.getMassStart(), resultPlot.getMassRange(), resultPlot.getIntensityRange());
        }
    }

    /**
     * ?
     * ???
     * @param start
     * @param end
     */
    public int getMaxIntensity(double start, double end) {
        PeakData qPaek = queryPlot.getPeaks(0);
        PeakData dPeak = resultPlot.getPeaks(0);
        int qm = 0;
        int dm = 0;
        if (qPaek != null)
            qm = qPaek.getMaxIntensity(start, end);
        if (dPeak != null)
            dm = dPeak.getMaxIntensity(start, end);
        return Math.max(qm, dm);
    }

    /**
     * ?
     */
    private void createWindow() {

        // ??
        ToolTipManager ttm = ToolTipManager.sharedInstance();
        ttm.setInitialDelay(50);
        ttm.setDismissDelay(8000);

        // Search?
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        Border border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
                new EmptyBorder(1, 1, 1, 1));
        mainPanel.setBorder(border);

        // *********************************************************************
        // User File Query
        // *********************************************************************
        DefaultTableModel fileDm = new DefaultTableModel();
        fileSorter = new TableSorter(fileDm, TABLE_QUERY_FILE);
        queryFileTable = new JTable(fileSorter) {
            @Override
            public boolean isCellEditable(int row, int column) {
                //            super.isCellEditable(row, column);
                // ??????
                return false;
            }
        };
        queryFileTable.addMouseListener(new TblMouseListener());
        fileSorter.setTableHeader(queryFileTable.getTableHeader());
        queryFileTable.setRowSelectionAllowed(true);
        queryFileTable.setColumnSelectionAllowed(false);
        queryFileTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        String[] col = { COL_LABEL_NO, COL_LABEL_NAME, COL_LABEL_ID };
        ((DefaultTableModel) fileSorter.getTableModel()).setColumnIdentifiers(col);
        (queryFileTable.getColumn(queryFileTable.getColumnName(0))).setPreferredWidth(44);
        (queryFileTable.getColumn(queryFileTable.getColumnName(1))).setPreferredWidth(LEFT_PANEL_WIDTH - 44);
        (queryFileTable.getColumn(queryFileTable.getColumnName(2))).setPreferredWidth(70);

        ListSelectionModel lm = queryFileTable.getSelectionModel();
        lm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lm.addListSelectionListener(new LmFileListener());
        queryFilePane = new JScrollPane(queryFileTable);
        queryFilePane.addMouseListener(new PaneMouseListener());
        queryFilePane.setPreferredSize(new Dimension(300, 300));

        // *********************************************************************
        // Result
        // *********************************************************************
        DefaultTableModel resultDm = new DefaultTableModel();
        resultSorter = new TableSorter(resultDm, TABLE_RESULT);
        resultTable = new JTable(resultSorter) {
            @Override
            public String getToolTipText(MouseEvent me) {
                //            super.getToolTipText(me);
                // ?????
                Point pt = me.getPoint();
                int row = rowAtPoint(pt);
                if (row < 0) {
                    return null;
                } else {
                    int nameCol = getColumnModel().getColumnIndex(COL_LABEL_NAME);
                    return " " + getValueAt(row, nameCol) + " ";
                }
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                //            super.isCellEditable(row, column);
                // ??????
                return false;
            }
        };
        resultTable.addMouseListener(new TblMouseListener());
        resultSorter.setTableHeader(resultTable.getTableHeader());

        JPanel dbPanel = new JPanel();
        dbPanel.setLayout(new BorderLayout());
        resultPane = new JScrollPane(resultTable);
        resultPane.addMouseListener(new PaneMouseListener());

        resultTable.setRowSelectionAllowed(true);
        resultTable.setColumnSelectionAllowed(false);
        resultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        String[] col2 = { COL_LABEL_NAME, COL_LABEL_SCORE, COL_LABEL_HIT, COL_LABEL_ID, COL_LABEL_ION,
                COL_LABEL_CONTRIBUTOR, COL_LABEL_NO };

        resultDm.setColumnIdentifiers(col2);
        (resultTable.getColumn(resultTable.getColumnName(0))).setPreferredWidth(LEFT_PANEL_WIDTH - 180);
        (resultTable.getColumn(resultTable.getColumnName(1))).setPreferredWidth(70);
        (resultTable.getColumn(resultTable.getColumnName(2))).setPreferredWidth(20);
        (resultTable.getColumn(resultTable.getColumnName(3))).setPreferredWidth(70);
        (resultTable.getColumn(resultTable.getColumnName(4))).setPreferredWidth(20);
        (resultTable.getColumn(resultTable.getColumnName(5))).setPreferredWidth(70);
        (resultTable.getColumn(resultTable.getColumnName(6))).setPreferredWidth(50);

        ListSelectionModel lm2 = resultTable.getSelectionModel();
        lm2.addListSelectionListener(new LmResultListener());

        resultPane.setPreferredSize(new Dimension(LEFT_PANEL_WIDTH, 200));
        dbPanel.add(resultPane, BorderLayout.CENTER);

        // *********************************************************************
        // DB Query
        // *********************************************************************
        DefaultTableModel dbDm = new DefaultTableModel();
        querySorter = new TableSorter(dbDm, TABLE_QUERY_DB);
        queryDbTable = new JTable(querySorter) {
            @Override
            public boolean isCellEditable(int row, int column) {
                //            super.isCellEditable(row, column);
                // ??????
                return false;
            }
        };
        queryDbTable.addMouseListener(new TblMouseListener());
        querySorter.setTableHeader(queryDbTable.getTableHeader());
        queryDbPane = new JScrollPane(queryDbTable);
        queryDbPane.addMouseListener(new PaneMouseListener());

        int h = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        queryDbPane.setPreferredSize(new Dimension(LEFT_PANEL_WIDTH, h));
        queryDbTable.setRowSelectionAllowed(true);
        queryDbTable.setColumnSelectionAllowed(false);
        queryDbTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        String[] col3 = { COL_LABEL_ID, COL_LABEL_NAME, COL_LABEL_CONTRIBUTOR, COL_LABEL_NO };
        DefaultTableModel model = (DefaultTableModel) querySorter.getTableModel();
        model.setColumnIdentifiers(col3);

        // 
        queryDbTable.getColumn(queryDbTable.getColumnName(0)).setPreferredWidth(70);
        queryDbTable.getColumn(queryDbTable.getColumnName(1)).setPreferredWidth(LEFT_PANEL_WIDTH - 70);
        queryDbTable.getColumn(queryDbTable.getColumnName(2)).setPreferredWidth(70);
        queryDbTable.getColumn(queryDbTable.getColumnName(3)).setPreferredWidth(50);

        ListSelectionModel lm3 = queryDbTable.getSelectionModel();
        lm3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lm3.addListSelectionListener(new LmQueryDbListener());

        // ?
        JPanel btnPanel = new JPanel();
        btnName.addActionListener(new BtnSearchNameListener());
        btnAll.addActionListener(new BtnAllListener());
        btnPanel.add(btnName);
        btnPanel.add(btnAll);

        parentPanel2 = new JPanel();
        parentPanel2.setLayout(new BoxLayout(parentPanel2, BoxLayout.PAGE_AXIS));
        parentPanel2.add(btnPanel);
        parentPanel2.add(queryDbPane);

        // ?
        JPanel dispModePanel = new JPanel();
        isDispSelected = dispSelected.isSelected();
        isDispRelated = dispRelated.isSelected();
        if (isDispSelected) {
            resultTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        } else if (isDispRelated) {
            resultTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        }
        Object[] retRadio = new Object[] { dispSelected, dispRelated };
        for (int i = 0; i < retRadio.length; i++) {
            ((JRadioButton) retRadio[i]).addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    if (isDispSelected != dispSelected.isSelected() || isDispRelated != dispRelated.isSelected()) {

                        isDispSelected = dispSelected.isSelected();
                        isDispRelated = dispRelated.isSelected();

                        // ??
                        resultTable.clearSelection();
                        resultPlot.clear();
                        compPlot.setPeaks(null, 1);
                        resultPlot.setPeaks(null, 0);
                        setAllPlotAreaRange();
                        pkgView.initResultRecInfo();

                        if (isDispSelected) {
                            resultTable.getSelectionModel()
                                    .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                        } else if (isDispRelated) {
                            resultTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                        }
                    }
                }
            });
        }
        ButtonGroup disGroup = new ButtonGroup();
        disGroup.add(dispSelected);
        disGroup.add(dispRelated);
        dispModePanel.add(lbl2);
        dispModePanel.add(dispSelected);
        dispModePanel.add(dispRelated);

        JPanel paramPanel = new JPanel();
        paramPanel.add(etcPropertyButton);
        etcPropertyButton.setMargin(new Insets(0, 10, 0, 10));
        etcPropertyButton.addActionListener(new ActionListener() {
            private ParameterSetWindow ps = null;

            public void actionPerformed(ActionEvent e) {
                // ??????????
                if (!isSubWindow) {
                    ps = new ParameterSetWindow(getParentFrame());
                } else {
                    ps.requestFocus();
                }
            }
        });

        JPanel optionPanel = new JPanel();
        optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.Y_AXIS));
        optionPanel.add(dispModePanel);
        optionPanel.add(paramPanel);

        // PackageView?????
        pkgView = new PackageViewPanel();
        pkgView.initAllRecInfo();

        queryTabPane.addTab("DB", parentPanel2);
        queryTabPane.setToolTipTextAt(TAB_ORDER_DB, "Query from DB.");
        queryTabPane.addTab("File", queryFilePane);
        queryTabPane.setToolTipTextAt(TAB_ORDER_FILE, "Query from user file.");
        queryTabPane.setSelectedIndex(TAB_ORDER_DB);
        queryTabPane.setFocusable(false);
        queryTabPane.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {

                // ?
                queryPlot.clear();
                compPlot.clear();
                resultPlot.clear();
                queryPlot.setPeaks(null, 0);
                compPlot.setPeaks(null, 1);
                resultPlot.setPeaks(null, 0);

                // PackageView?
                pkgView.initAllRecInfo();

                // DB Hit?
                if (resultTabPane.getTabCount() > 0) {
                    resultTabPane.setSelectedIndex(0);
                }
                DefaultTableModel dataModel = (DefaultTableModel) resultSorter.getTableModel();
                dataModel.setRowCount(0);
                hitLabel.setText(" ");

                // DB?User File??????
                queryTabPane.update(queryTabPane.getGraphics());
                if (queryTabPane.getSelectedIndex() == TAB_ORDER_DB) {
                    parentPanel2.update(parentPanel2.getGraphics());
                    updateSelectQueryTable(queryDbTable);
                } else if (queryTabPane.getSelectedIndex() == TAB_ORDER_FILE) {
                    queryFilePane.update(queryFilePane.getGraphics());
                    updateSelectQueryTable(queryFileTable);
                }
            }
        });

        //       
        JPanel queryPanel = new JPanel();
        queryPanel.setLayout(new BorderLayout());
        queryPanel.add(queryTabPane, BorderLayout.CENTER);
        queryPanel.add(optionPanel, BorderLayout.SOUTH);
        queryPanel.setMinimumSize(new Dimension(0, 170));

        JPanel jtp2Panel = new JPanel();
        jtp2Panel.setLayout(new BorderLayout());
        jtp2Panel.add(dbPanel, BorderLayout.CENTER);
        jtp2Panel.add(hitLabel, BorderLayout.SOUTH);
        jtp2Panel.setMinimumSize(new Dimension(0, 70));
        Color colorGreen = new Color(0, 128, 0);
        hitLabel.setForeground(colorGreen);

        resultTabPane.addTab("Result", jtp2Panel);
        resultTabPane.setToolTipTextAt(TAB_RESULT_DB, "Result of DB hit.");
        resultTabPane.setFocusable(false);

        queryPlot.setMinimumSize(new Dimension(0, 100));
        compPlot.setMinimumSize(new Dimension(0, 120));
        resultPlot.setMinimumSize(new Dimension(0, 100));
        int height = initAppletHight / 3;
        JSplitPane jsp_cmp2db = new JSplitPane(JSplitPane.VERTICAL_SPLIT, compPlot, resultPlot);
        JSplitPane jsp_qry2cmp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, queryPlot, jsp_cmp2db);
        jsp_cmp2db.setDividerLocation(height);
        jsp_qry2cmp.setDividerLocation(height - 25);
        jsp_qry2cmp.setMinimumSize(new Dimension(190, 0));

        viewTabPane.addTab("Compare View", jsp_qry2cmp);
        viewTabPane.addTab("Package View", pkgView);
        viewTabPane.setToolTipTextAt(TAB_VIEW_COMPARE, "Comparison of query and result spectrum.");
        viewTabPane.setToolTipTextAt(TAB_VIEW_PACKAGE, "Package comparison of query and result spectrum.");
        viewTabPane.setSelectedIndex(TAB_VIEW_COMPARE);
        viewTabPane.setFocusable(false);

        JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, queryPanel, resultTabPane);
        jsp.setDividerLocation(310);
        jsp.setMinimumSize(new Dimension(180, 0));
        jsp.setOneTouchExpandable(true);

        JSplitPane jsp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jsp, viewTabPane);
        int divideSize = (int) (initAppletWidth * 0.4);
        divideSize = (divideSize >= 180) ? divideSize : 180;
        jsp2.setDividerLocation(divideSize);
        jsp2.setOneTouchExpandable(true);

        mainPanel.add(jsp2, BorderLayout.CENTER);
        add(mainPanel);

        queryPlot.setSearchPage(this);
        compPlot.setSearchPage(this);
        resultPlot.setSearchPage(this);

        setJMenuBar(MenuBarGenerator.generateMenuBar(this));
    }

    /**
     * DB
     * ???DB??
     * @param ps 
     * @param precursor 
     * @param queryName ???
     * @param queryKey 
     */
    private void searchDb(String[] ps, String precursor, String queryName, String queryKey) {
        initSearchParameterSetting();

        queryPlot.clear();
        compPlot.clear();
        resultPlot.clear();
        queryPlot.setPeaks(null, 0);
        compPlot.setPeaks(null, 1);
        resultPlot.setPeaks(null, 0);
        DefaultTableModel dataModel = (DefaultTableModel) resultSorter.getTableModel();
        dataModel.setRowCount(0);
        hitLabel.setText("");

        if (queryTabPane.getSelectedIndex() == TAB_ORDER_DB) {
            queryPlot.setSpectrumInfo(queryName, queryKey, precursor, PeakPanel.SP_TYPE_QUERY, false);
        } else if (queryTabPane.getSelectedIndex() == TAB_ORDER_FILE) {
            queryPlot.setSpectrumInfo(queryName, queryKey, precursor, PeakPanel.SP_TYPE_QUERY, true);
        }

        // ??????
        if (ps.length == 0
                || (ps.length == 1 && ps[0].split("\t")[0].equals("0") && ps[0].split("\t")[1].equals("0"))) {
            queryPlot.setNoPeak(true);
            StringBuilder sb = new StringBuilder();
            sb.append(" 0 Hit.    (");
            sb.append((PRECURSOR < 1) ? "" : "Precursor : " + PRECURSOR + ", ");
            sb.append("Tolerance : ");
            sb.append(" ");
            sb.append((tolUnit1.isSelected()) ? tolUnit1.getText() : tolUnit2.getText());
            sb.append(", Cutoff threshold : " + CUTOFF_THRESHOLD + ")");
            hitLabel.setText(sb.toString());

            //         hitLabel.setText(" 0 Hit.    ("
            //               + ((PRECURSOR < 1) ? "" : "Precursor : " + PRECURSOR + ", ")
            //               + "Tolerance : "
            //               + TOLERANCE
            //               + " "
            //               + ((tolUnit1.isSelected()) ? tolUnit1.getText() : tolUnit2.getText()) + ", Cutoff threshold : "
            //               + CUTOFF_THRESHOLD + ")");

            // ?
            this.setCursor(Cursor.getDefaultCursor());
            return;
        }

        // POST?
        final SearchQueryParam param = new SearchQueryParam(); // StringBuffer post = new StringBuffer();
        if (isRecInteg) {
            param.setInteg(true); //   post.append( "INTEG=true&" );
        } else if (isRecActu) {
            param.setInteg(false); //   post.append( "INTEG=false&" );
        }
        if (PRECURSOR > 0) {
            param.setPrecursor(PRECURSOR); //   post.append( "PRE=" + PRECURSOR + "&");
        }
        param.setCutoff(CUTOFF_THRESHOLD); //   post.append( "CUTOFF=" + CUTOFF_THRESHOLD + "&" );
        param.setTolerance(TOLERANCE); //   post.append( "TOLERANCE=" + TOLERANCE + "&" );
        if (tolUnit2.isSelected()) {
            param.setTolUnit(ToleranceUnit.PPM.getLabel()); //   post.append( "TOLUNIT=ppm&" );
        } else {
            param.setTolUnit(ToleranceUnit.UNIT.getLabel()); //   post.append( "TOLUNIT=unit&" );
        }
        StringBuffer sbInstance = new StringBuffer(); //   post.append( "INST=" );
        boolean isAllInstanceSelected = true;
        for (Entry<String, Boolean> entry : isInstCheck.entrySet()) {
            if (entry.getValue()) {
                if (sbInstance.length() > 0) {
                    sbInstance.append(",");
                }
                sbInstance.append(entry.getKey());
            } else {
                isAllInstanceSelected = false;
            }
        }

        //      for (Iterator i=isInstCheck.keySet().iterator(); i.hasNext();) {
        //         String key = (String)i.next();
        //         
        //         if ( (isInstCheck.get(key)) ) {
        //            if (sbInstance.length() > 0) {
        //               sbInstance.append( "," );
        //            }
        //            sbInstance.append( key );
        //         } else {
        //            isInstAll = false;
        //         }
        //      }

        if (isAllInstanceSelected) {
            if (sbInstance.length() > 0) {
                sbInstance.append(",");
            }
            sbInstance.append("ALL");
        }
        param.setInstType(sbInstance.toString()); // post.append( instTmp.toString() + "&" );

        StringBuffer sbMs = new StringBuffer(); // post.append( "MS=" );
        boolean isAllMsSelected = true;
        for (Entry<String, Boolean> entry : isMsCheck.entrySet()) {
            if (entry.getValue()) {
                if (sbMs.length() > 0) {
                    sbMs.append(",");
                }
                sbMs.append(entry.getKey());
            } else {
                isAllMsSelected = false;
            }
        }

        //      for (Iterator i=isMsCheck.keySet().iterator(); i.hasNext(); ) {
        //         String key = (String)i.next();
        //         
        //         if ( (isMsCheck.get(key)) ) {
        //            if (msTmp.length() > 0) {
        //               msTmp.append( "," );
        //            }
        //            msTmp.append( key );
        //         } else {
        //            isMsAll = false;
        //         }
        //      }

        if (isAllMsSelected) {
            if (sbMs.length() > 0) {
                sbMs.append(",");
            }
            sbMs.append("ALL");
        }
        param.setMsType(sbMs.toString()); // post.append( msTmp.toString() + "&" );

        if (isIonRadio.get(IonMode.POSITIVE.getKey())) { // if (isIonRadio.get("Posi")) {
            param.setIon(1); // post.append( "ION=1&" );
        } else if (isIonRadio.get(IonMode.NEGATIVE.getKey())) { // } else if (isIonRadio.get("Nega")) {
            param.setIon(-1); // post.append( "ION=-1&" );
        } else {
            param.setIon(0); // post.append( "ION=0&");
        }

        StringBuffer sbPeakValue = new StringBuffer(); // post.append( "VAL=" );
        for (int i = 0; i < ps.length; i++) {
            sbPeakValue.append(ps[i].replace("\t", ",") + "@");
        }
        param.setPeak(sbPeakValue.toString());

        // ???
        setOperationEnbled(false);

        // ?
        dlg.showDialog();

        //      this.param = post.toString();
        this.ps = ps;
        SwingWorker worker = new SwingWorker() {
            private ArrayList<String> result = null;

            public Object construct() {
                // ??-??CGI
                SearchLogic searchLogic = new SearchLogic();
                result = searchLogic.getSearchResult(param);
                return null;
                //            String cgiType = MassBankCommon.CGI_TBL[MassBankCommon.CGI_TBL_NUM_TYPE][MassBankCommon.CGI_TBL_TYPE_SEARCH];
                //            result = mbcommon.execMultiDispatcher(baseUrl, cgiType, SearchPage.this.param);
                //            return null;
            }

            public void finished() {
                // ???
                setOperationEnbled(true);

                // ???
                dlg.hideDialog();

                int total = 0;
                if (result != null && result.size() > 0) {
                    total = result.size();

                    List<GuiResultTableRow> guiResultTableRows = new ArrayList<GuiResultTableRow>();
                    // ?DBTable?
                    for (int i = 0; i < total; i++) {
                        String line = (String) result.get(i);
                        String[] item = line.replace("\n", StringUtils.EMPTY).split("\t");
                        String recordId = item[0];
                        String recordTitle = item[1];
                        // Score, Hit
                        String strScore = StringUtils.EMPTY;
                        String strHit = StringUtils.EMPTY;
                        String hitScore = item[2];
                        int pos = hitScore.indexOf(".");
                        if (pos > 0) {
                            strScore = "0" + hitScore.substring(pos);
                            strHit = hitScore.substring(0, pos);
                        } else {
                            strScore = "0";
                            strHit = hitScore;
                        }
                        Double score = Double.parseDouble(strScore);
                        Integer hit = Integer.parseInt(strHit);

                        // Ion
                        int iIon = Integer.parseInt(item[3]);
                        String strIonMode = StringUtils.EMPTY;
                        if (iIon > 0) {
                            strIonMode = "P";
                        } else if (iIon < 0) {
                            strIonMode = "N";
                        } else {
                            strIonMode = "-";
                        }

                        // SiteName
                        String contributor = SiteUtil.getSiteNameByRecordId(recordId);
                        GuiResultTableRow guiResultTableRow = new GuiResultTableRow((i + 1), recordId, recordTitle,
                                contributor, score, hit, strIonMode);
                        guiResultTableRows.add(guiResultTableRow);
                    }

                    fillGuiResultTableData(guiResultTableRows);
                }

                PeakData peak = new PeakData(SearchPage.this.ps);
                queryPlot.setPeaks(peak, 0);
                compPlot.setPeaks(peak, 0);
                resultTabPane.setSelectedIndex(0);
                setAllPlotAreaRange(queryPlot);
                SearchPage.this.setCursor(Cursor.getDefaultCursor());

                StringBuilder sbHitLabel = new StringBuilder();
                sbHitLabel.append(" ");
                sbHitLabel.append(total);
                sbHitLabel.append(" Hit.    (");
                sbHitLabel.append((PRECURSOR < 1) ? "" : "Precursor : " + PRECURSOR + ", ");
                sbHitLabel.append("Tolerance : ");
                sbHitLabel.append(TOLERANCE);
                sbHitLabel.append(" ");
                sbHitLabel.append((tolUnit1.isSelected()) ? tolUnit1.getText() : tolUnit2.getText());
                sbHitLabel.append(", Cutoff threshold : ");
                sbHitLabel.append(CUTOFF_THRESHOLD);
                sbHitLabel.append(")");
                hitLabel.setText(sbHitLabel.toString());
                hitLabel.setToolTipText(sbHitLabel.toString());

                //            hitLabel.setText(" "
                //                  + total
                //                  + " Hit.    ("
                //                  + ((PRECURSOR < 1) ? "" : "Precursor : " + PRECURSOR + ", ")
                //                  + "Tolerance : "
                //                  + TOLERANCE
                //                  + " "
                //                  + ((tolUnit1.isSelected()) ? tolUnit1.getText()
                //                        : tolUnit2.getText()) + ", Cutoff threshold : "
                //                  + CUTOFF_THRESHOLD + ")");

                //            hitLabel.setToolTipText(" "
                //                  + total
                //                  + " Hit.    ("
                //                  + ((PRECURSOR < 1) ? "" : "Precursor : " + PRECURSOR + ", ")
                //                  + "Tolerance : "
                //                  + TOLERANCE
                //                  + " "
                //                  + ((tolUnit1.isSelected()) ? tolUnit1.getText()
                //                        : tolUnit2.getText()) + ", Cutoff threshold : "
                //                  + CUTOFF_THRESHOLD + ")");
            }
        };
        worker.start();
    }

    /**
     * ??
     */
    private void updateSelectQueryTable(JTable tbl) {

        // ?
        this.setCursor(waitCursor);

        int selRow = tbl.getSelectedRow();
        if (selRow >= 0) {
            tbl.clearSelection();
            Color defColor = tbl.getSelectionBackground();
            tbl.setRowSelectionInterval(selRow, selRow);
            tbl.setSelectionBackground(Color.PINK);
            tbl.update(tbl.getGraphics());
            tbl.setSelectionBackground(defColor);
        }
        // ?
        this.setCursor(Cursor.getDefaultCursor());
    }

    /**
     * ?
     * DB???
     * @param searchName 
     */
    private void getSpectrumForQuery(String searchName) {

        List<String> result = new ArrayList<String>();
        try {
            DbAccessor.createConnection();
            CompoundLogic compoundLogic = new CompoundLogic();
            LOGGER.info("search records by keyword || " + searchName);
            List<Compound> compoundList = compoundLogic.getCompoundListByKeyword(searchName);
            DbAccessor.closeConnection();
            for (Compound compound : compoundList) {
                String prefix = SiteUtil.getServerPrefixByRecordId(compound.getId());
                result.add(String.format("%s\t%s\t%s", compound.getTitle(), compound.getId(), prefix));
            }
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
            return;
        }

        List<GuiDbTableRow> oGuiDbTableRows = new ArrayList<GuiDbTableRow>();
        for (int i = 0; i < result.size(); i++) {
            String nameId = (String) result.get(i);
            String[] cutNameId = nameId.split("\t");
            String index = String.valueOf(i + 1);
            String recordId = cutNameId[1];
            String recordTitle = cutNameId[0];
            String sitePrefix = cutNameId[2];
            String contributor = SiteUtil.getSiteNameByRecordIdPrefix(sitePrefix);
            GuiDbTableRow guiDbTableRow = new GuiDbTableRow(index, recordId, recordTitle, contributor);
            oGuiDbTableRows.add(guiDbTableRow);
        }

        if (StringUtils.isBlank(searchName)) {
            for (GuiDbTableRow row : oGuiDbTableRows) {
                guiDbTableRowMap.put(row.getRecordId(), row);
            }
        }

        fillGuiDbTableData(oGuiDbTableRows);
    }

    private void fillGuiDbTableData(List<GuiDbTableRow> rows) {
        DefaultTableModel dataModel = (DefaultTableModel) querySorter.getTableModel();
        dataModel.setRowCount(0);
        Collections.sort(rows);
        if (rows != null && rows.size() > 0) {
            for (GuiDbTableRow row : rows) {
                dataModel.addRow(new String[] { row.getRecordId(), row.getRecordTitle(), row.getContributor(),
                        row.getIndex() });
            }
        }
    }

    private void fillGuiResultTableData(List<GuiResultTableRow> rows) {
        DefaultTableModel dataModel = (DefaultTableModel) resultSorter.getTableModel();
        dataModel.setRowCount(0);
        Collections.sort(rows);
        if (rows != null && rows.size() > 0) {
            for (GuiResultTableRow row : rows) {
                dataModel.addRow(new Object[] { row.getRecordTitle(), row.getScore(), row.getHit(),
                        row.getRecordId(), row.getIonMode(), row.getContributor(), row.getIndex() });
            }
        }
    }

    /**
     * 
     * @param selectIndex ?
     */
    private void showRecordPage(JTable eventTbl) {
        // TODO
        // Record Table double click -> open browser, Result Record Table double click -> open browser, Result Record Table -> right click -> show record
        CommonUtil.openBrowser(Constant.ExternalUrl.SHOW_RECORD_PAGE);

        //      int selRows[] = eventTbl.getSelectedRows();
        //      int idCol = eventTbl.getColumnModel().getColumnIndex(COL_LABEL_ID);
        //      int siteCol = eventTbl.getColumnModel().getColumnIndex(COL_LABEL_CONTRIBUTOR);
        //      
        //      // ????(id)?
        //      String id = (String)eventTbl.getValueAt(selRows[0], idCol);
        //      String siteName = (String)eventTbl.getValueAt(selRows[0], siteCol);
        //      String site = "0";
        ////      for (int i=0; i<siteNameList.length; i++) {
        ////         if (siteName.equals(siteNameList[i])) {
        ////            site = Integer.toString(i);
        ////            break;
        ////         }
        ////      }
        //      
        //      // CGI??
        //      String typeName = MassBankCommon.CGI_TBL[MassBankCommon.CGI_TBL_NUM_TYPE][MassBankCommon.CGI_TBL_TYPE_DISP];
        //      String reqUrl = baseUrl + "jsp/" + MassBankCommon.DISPATCHER_NAME
        //            + "?type=" + typeName + "&id=" + id + "&site=" + site;
        //        LOGGER.info("open browser with " + reqUrl);
        //        try {
        //          Desktop.getDesktop().browse(new URI(reqUrl));
        //        } catch (IOException | URISyntaxException ex) {
        //            LOGGER.error(ex.getMessage(),ex);
        //        }
    }

    /**
     * ?
     * @param e 
     */
    private void recListPopup(MouseEvent e) {
        JTable tbl = null;
        JScrollPane pane = null;
        try {
            tbl = (JTable) e.getSource();
        } catch (ClassCastException cce) {
            pane = (JScrollPane) e.getSource();
            if (pane.equals(queryDbPane)) {
                tbl = queryDbTable;
            } else if (pane.equals(resultPane)) {
                tbl = resultTable;
            }
            if (pane.equals(queryFilePane)) {
                tbl = queryFileTable;
            }
        }
        int rowCnt = tbl.getSelectedRows().length;

        JMenuItem item1 = new JMenuItem("Show Record");
        item1.addActionListener(new PopupShowRecordListener(tbl));
        JMenuItem item2 = new JMenuItem("Multiple Display");
        item2.addActionListener(new PopupMultipleDisplayListener(tbl));

        // ?
        if (tbl.equals(queryFileTable)) {
            item1.setEnabled(false);
            item2.setEnabled(false);
        } else if (rowCnt == 0) {
            item1.setEnabled(false);
            item2.setEnabled(false);
        } else if (rowCnt == 1) {
            item1.setEnabled(true);
            item2.setEnabled(false);
        } else if (rowCnt > 1) {
            item1.setEnabled(false);
            item2.setEnabled(true);
        }

        // ?
        JPopupMenu popup = new JPopupMenu();
        popup.add(item1);
        if (tbl.equals(resultTable)) {
            popup.add(item2);
        }
        popup.show(e.getComponent(), e.getX(), e.getY());
    }

    /**
     * Precursor m/z?
     */
    private void initPreInfo() {
        //      // Cookie?Cookie?Precursor?
        //      ArrayList<String> valueList = cm.getCookie(COOKIE_PRE);
        //      
        //      // Cookie???
        //      if (valueList.size() != 0) {
        //         try {
        //            PRECURSOR = Integer.valueOf(valueList.get(0));
        //         } catch (Exception e) {
        //            // PRECURSOR?
        //         }
        //      } else {
        PRECURSOR = -1;
        //         valueList.add(String.valueOf(PRECURSOR));
        //         cm.setCookie(COOKIE_PRE, valueList);
        //      }
    }

    /**
     * Tolerance?
     */
    private void initTolInfo() {
        // set search param 'Tolerance'
        TOLERANCE = SystemProperties.getInstance().getDefaultTolerance();
        // set search param 'Tolerance unit'
        String toleranceUnit = SystemProperties.getInstance().getDefaultToleranceUnit();
        if (tolUnit2.getText().equals(toleranceUnit)) {
            tolUnit1.setSelected(false);
            tolUnit2.setSelected(true);
        } else {
            tolUnit1.setSelected(true);
            tolUnit2.setSelected(false);
        }

        //      // Cookie?Cookie?Tolerance?
        //      ArrayList<String> valueList = cm.getCookie(COOKIE_TOL);
        //      
        //      // Cookie???
        //      if (valueList.size() != 0) {
        //         try {
        //            TOLERANCE = Float.valueOf(valueList.get(0));
        //         } catch (Exception e) {
        //            // TOLERANCE?
        //         }
        //         
        //         if (valueList.contains(tolUnit2.getText())) {
        //            tolUnit1.setSelected(false);
        //            tolUnit2.setSelected(true);
        //         } else {
        //            tolUnit1.setSelected(true);
        //            tolUnit2.setSelected(false);
        //         }
        //      } else {
        //         TOLERANCE = SystemProperties.getInstance().getDefaultTolerance();
        //         valueList.add(String.valueOf(TOLERANCE));
        //         if (tolUnit1.isSelected()) {
        //            valueList.add(tolUnit1.getText());   
        //         }
        //         else {
        //            valueList.add(tolUnit2.getText());
        //         }
        //         cm.setCookie(COOKIE_TOL, valueList);
        //      }
    }

    /**
     * Cutoff Threshold?
     */
    private void initCutoffInfo() {
        CUTOFF_THRESHOLD = SystemProperties.getInstance().getDefaultCutoffThreshold();

        //      // Cookie?Cookie?Cutoff Threshold?
        //      ArrayList<String> valueList = cm.getCookie(COOKIE_CUTOFF);
        //      
        //      // Cookie???
        //      if (valueList.size() != 0) {
        //         try {
        //              CUTOFF_THRESHOLD = Integer.parseInt(valueList.get(0));
        ////              CUTOFF_THRESHOLD = Integer.valueOf(valueList.get(0));
        //         } catch (Exception e) {
        //            // CUTOFF_THRESHOLD?
        //         }
        //      } else {
        //         CUTOFF_THRESHOLD = SystemProperties.getInstance().getCutoffThreshold();
        //         valueList.add(String.valueOf(CUTOFF_THRESHOLD));
        //         cm.setCookie(COOKIE_CUTOFF, valueList);
        //      }
    }

    /**
     * ?
     * ???????
     * ????[Cookie][]?????
     * ??1???????????????
     */
    private void initInstInfo() {
        instCheck = new LinkedHashMap<String, JCheckBox>();
        isInstCheck = new HashMap<String, Boolean>();
        instGroup = instInfo.getTypeGroup();

        // Cookie?Cookie????
        List<String> valueGetList = Arrays.asList(SystemProperties.getInstance().getDefaultInstanceTypeList());
        //        ArrayList<String> valueGetList = cm.getCookie(COOKIE_INST);
        List<String> valueSetList = new ArrayList<String>();

        boolean checked = false;
        LOGGER.info("instInfo.getTypeGroup().size() -> " + instGroup.size());
        for (Entry<String, List<String>> entry : instGroup.entrySet()) {
            //      for (Iterator i=instGroup.keySet().iterator(); i.hasNext(); ) {
            //         String key = (String)i.next();

            //         List<String> list = instGroup.get(key);
            //          LOGGER.info("instGroup.get(  "+key+"  ).size() -> " + list.size());
            List<String> list = entry.getValue();
            for (String val : list) {
                //         for ( int j = 0; j < list.size(); j++ ) {
                //            String val = list.get(j);

                JCheckBox chkBox;

                // Cookie???
                if (valueGetList.size() != 0) {
                    if (valueGetList.contains(val)) {
                        chkBox = new JCheckBox(val, true);
                        checked = true;
                    } else {
                        chkBox = new JCheckBox(val, false);
                    }
                } else {
                    if (isDefaultInst(val)) { // ?? 
                        chkBox = new JCheckBox(val, true);
                        checked = true;
                        valueSetList.add(val);
                    } else {
                        chkBox = new JCheckBox(val, false);
                    }
                }

                instCheck.put(val, chkBox);
                isInstCheck.put(val, chkBox.isSelected());
            }
        }

        // ????????
        if (instCheck.size() == 0 && isInstCheck.size() == 0) {
            JOptionPane.showMessageDialog(null, "Instrument Type is not registered in the database.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // ????????1?????????????
        if (!checked) {
            for (Iterator i = instCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                ((JCheckBox) instCheck.get(key)).setSelected(true);
                isInstCheck.put(key, true);
                valueSetList.add(key);
            }
        }

        // ????Cookie??????Cookie?
        if (valueGetList.size() == 0) {
            SystemProperties.setDefaultInstanceTypeList(valueSetList);
            //         cm.setCookie(COOKIE_INST, valueSetList);
        }
    }

    /**
     * MS?
     * ?MS??????
     * ????[Cookie][]?????
     * ??1???????????????
     */
    private void initMsInfo() {
        msCheck = new LinkedHashMap<String, JCheckBox>();
        isMsCheck = new HashMap<String, Boolean>();

        // Cookie?Cookie?MS???
        List<String> valueGetList = Arrays.asList(SystemProperties.getInstance().getDefaultMsList());
        //        ArrayList<String> valueGetList = cm.getCookie(COOKIE_MS);
        List<String> valueSetList = new ArrayList<String>();

        boolean checked = false;

        List<String> list = Arrays.asList(instInfo.getMsAll());

        //      LOGGER.info("instInfo.getMsAll().length -> " + list.size());
        for (String val : list) {
            //      for ( int j=0; j<list.size(); j++ ) {
            //         String val = list.get(j);

            JCheckBox chkBox;

            // Cookie???
            if (valueGetList.size() != 0) {
                if (valueGetList.contains(val)) {
                    chkBox = new JCheckBox(val, true);
                    checked = true;
                } else {
                    chkBox = new JCheckBox(val, false);
                }
            } else {
                chkBox = new JCheckBox(val, true);
                checked = true;
                valueSetList.add(val);
            }

            msCheck.put(val, chkBox);
            isMsCheck.put(val, chkBox.isSelected());
        }

        // MS????????
        if (msCheck.size() == 0 && isMsCheck.size() == 0) {
            JOptionPane.showMessageDialog(null, "MS Type is not registered in the database.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // ???????MS?1?????????????
        if (!checked) {
            for (Iterator i = msCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                ((JCheckBox) msCheck.get(key)).setSelected(true);
                isMsCheck.put(key, true);
                valueSetList.add(key);
            }
        }

        // ????Cookie??????Cookie?
        if (valueGetList.size() == 0) {
            SystemProperties.setDefaultMsList(valueSetList);
            //         cm.setCookie(COOKIE_MS, valueSetList);
        }
    }

    /**
     * ?
     */
    private void initIonInfo() {
        final String keyPosi = IonMode.POSITIVE.getKey();
        final String keyNega = IonMode.NEGATIVE.getKey();
        final String keyBoth = IonMode.BOTH.getKey();
        //      final String keyPosi = "Posi";
        //      final String keyNega = "Nega";
        //      final String keyBoth = "Both";

        ionRadio = new LinkedHashMap<String, JRadioButton>();
        isIonRadio = new HashMap<String, Boolean>();

        // Cookie?Cookie????
        List<String> valueList = new ArrayList<String>();
        for (String val : SystemProperties.getInstance().getDefaultIonList()) {
            valueList.add(val.toUpperCase());
        }
        //        ArrayList<String> valueList = cm.getCookie(COOKIE_ION);

        JRadioButton ionPosi = new JRadioButton(IonMode.POSITIVE.getLabel());
        JRadioButton ionNega = new JRadioButton(IonMode.NEGATIVE.getLabel());
        JRadioButton ionBoth = new JRadioButton(IonMode.BOTH.getLabel());

        // Cookie???
        if (valueList.size() != 0) {
            ionPosi.setSelected(valueList.contains(keyPosi));
            ionNega.setSelected(valueList.contains(keyNega));
            ionBoth.setSelected(valueList.contains(keyBoth));
        } else {
            ionPosi.setSelected(true);
            ionNega.setSelected(false);
            ionBoth.setSelected(false);
            valueList.add(keyPosi);
            SystemProperties.setDefaultIonList(valueList);
            //         cm.setCookie(COOKIE_ION, valueList);
        }

        ionRadio.put(keyPosi, ionPosi);
        ionRadio.put(keyNega, ionNega);
        ionRadio.put(keyBoth, ionBoth);
        isIonRadio.put(keyPosi, ionPosi.isSelected());
        isIonRadio.put(keyNega, ionNega.isSelected());
        isIonRadio.put(keyBoth, ionBoth.isSelected());
    }

    /**
     * ?
     * ?"ESI"?"APPI"?"MALDI"????
     * @param inst 
     */
    private boolean isDefaultInst(String inst) {

        if (inst.indexOf("ESI") != -1 || inst.indexOf("APPI") != -1 || inst.indexOf("MALDI") != -1) {

            return true;
        }
        return false;
    }

    /**
     * ??
     */
    protected Frame getParentFrame() {
        return (JFrame) SwingUtilities.getRoot(this);
    }

    protected Frame getFrame() {
        for (Container p = getParent(); p != null; p = p.getParent()) {
            if (p instanceof Frame)
                return (Frame) p;
        }
        return null;
    }

    /**
     * ??
     */
    private void setOperationEnbled(boolean value) {
        queryFileTable.setEnabled(value);
        queryDbTable.setEnabled(value);
        etcPropertyButton.setEnabled(value);
        btnName.setEnabled(value);
        btnAll.setEnabled(value);
        dispSelected.setEnabled(value);
        dispRelated.setEnabled(value);
        queryTabPane.setEnabled(value);
        resultTabPane.setEnabled(value);
        viewTabPane.setEnabled(value);
        lbl2.setEnabled(value);
    }

    /**
     * ParameterSetWindow
     */
    //   class ParameterSetWindow extends JFrame {
    class ParameterSetWindow extends AbstractDialog {

        private static final long serialVersionUID = -5319983912249144466L;
        private final int LABEL_SIZE_L = 0;
        private final int LABEL_SIZE_M = 1;
        private final int LABEL_SIZE_S = 2;
        private final JTextField preField;
        private final JTextField tolField;
        private final JTextField cutoffField;
        private boolean isTolUnit1 = tolUnit1.isSelected();
        private boolean isTolUnit2 = tolUnit2.isSelected();

        /**
         * 
         * @throws SQLException 
         */
        public ParameterSetWindow(Frame parent) {
            super(parent, "Search Parameter Setting");
            initSearchParameterSetting();

            // 
            setResizable(false);

            // ??
            ArrayList<Component> keyListenerList = new ArrayList<Component>();
            keyListenerList.add(this);

            // ?
            Container container = getContentPane();
            initMainContainer(container);

            JPanel delimPanel;
            JPanel labelPanel;
            JPanel itemPanel;

            // Tolerance
            labelPanel = newLabelPanel("Tolerance of m/z", " Tolerance of m/z. ", LABEL_SIZE_L, 2);

            JPanel tolPanel = new JPanel();
            tolPanel.setLayout(new BoxLayout(tolPanel, BoxLayout.X_AXIS));
            tolField = new JTextField(String.valueOf(TOLERANCE), 5);
            tolField.setHorizontalAlignment(JTextField.RIGHT);
            keyListenerList.add(tolField);
            keyListenerList.add(tolUnit1);
            keyListenerList.add(tolUnit2);
            ButtonGroup tolGroup = new ButtonGroup();
            tolGroup.add(tolUnit1);
            tolGroup.add(tolUnit2);
            tolPanel.add(tolUnit1);
            tolPanel.add(tolUnit2);

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(wrappTextPanel(tolField), itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(tolPanel, itemPanelGBC(0d, 0d, 1, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));
            delimPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            container.add(delimPanel, mainContainerGBC(0, 0, 1, 1));

            // Cutoff Thresholds
            labelPanel = newLabelPanel("Cutoff Threshold", " Cutoff threshold of intensities. ", LABEL_SIZE_L, 2);

            cutoffField = new JTextField(String.valueOf(CUTOFF_THRESHOLD), 5);
            cutoffField.setHorizontalAlignment(JTextField.RIGHT);
            keyListenerList.add(cutoffField);

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(wrappTextPanel(cutoffField), itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 1, 0, GridBagConstraints.REMAINDER, 1));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));
            delimPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            container.add(delimPanel, mainContainerGBC(0, 1, 1, 1));

            // Instrument Type
            labelPanel = newLabelPanel("Instrument Type", " Instrument type. ", LABEL_SIZE_L, 2);

            final JCheckBox chkBoxInstAll = new JCheckBox("All");
            chkBoxInstAll.setSelected(isInstAll());
            final JCheckBox chkBoxInstDefault = new JCheckBox("Default");
            chkBoxInstDefault.setSelected(isInstDefault());
            keyListenerList.add(chkBoxInstAll);
            keyListenerList.add(chkBoxInstDefault);

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(chkBoxInstAll, itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(0.1d, 0d, 1, 0, 1, 1));
            itemPanel.add(chkBoxInstDefault, itemPanelGBC(0d, 0d, 2, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 3, 0, GridBagConstraints.REMAINDER, 0));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));

            JPanel instPanel = new JPanel();
            initItemPanel(instPanel);

            int keyNum = 0;
            boolean isSep = false;
            for (Iterator i = instGroup.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                itemPanel = new JPanel();
                initItemPanel(itemPanel);

                // ???????
                List<String> list = instGroup.get(key);
                int valNum = 0;
                for (int j = 0; j < list.size(); j++) {
                    String val = list.get(j);

                    // 
                    if (keyNum != 0 && valNum == 0) {
                        itemPanel.add(new JSeparator(), itemPanelGBC(0d, 0d, 0, valNum, 3, 1));
                        valNum += 1;
                        isSep = true;
                    }

                    JCheckBox chkBox = (JCheckBox) instCheck.get(val);
                    keyListenerList.add(chkBox);
                    itemPanel.add(chkBox, itemPanelGBC(0d, 0d, 1, valNum, 1, 1));
                    valNum += 1;
                }

                // ??????
                if (valNum > 0) {
                    labelPanel = newLabelPanel(key, null, LABEL_SIZE_S, 2);
                    if (isSep) {
                        itemPanel.add(labelPanel, itemPanelGBC(0d, 0d, 0, 1, 1, 1));
                    } else {
                        itemPanel.add(labelPanel, itemPanelGBC(0d, 0d, 0, 0, 1, 1));
                    }
                    itemPanel.add(new JPanel(),
                            itemPanelGBC(1d, 1d, 2, 0, GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER));
                    instPanel.add(itemPanel, itemPanelGBC(0d, 0d, 0, keyNum, 1, 1));
                    keyNum += 1;
                    isSep = false;
                }
            }
            instPanel.add(new JPanel(),
                    itemPanelGBC(1d, 1d, 0, keyNum, GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER));
            JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            scroll.setPreferredSize(new Dimension(240, 250));
            scroll.getVerticalScrollBar().setUnitIncrement(60);
            scroll.setViewportView(instPanel);

            delimPanel.add(scroll, delimPanelGBC(0d, 0d, 1, 1, 1, 1));
            delimPanel.add(new JPanel(),
                    itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER));

            container.add(delimPanel, mainContainerGBC(0, 2, 1, 1));

            // MS Type
            labelPanel = newLabelPanel("MS Type", " MS type. ", LABEL_SIZE_L, 2);

            JPanel msPanel = new JPanel();
            msPanel.setLayout(new BoxLayout(msPanel, BoxLayout.X_AXIS));

            final JCheckBox chkBoxMsAll = new JCheckBox("All");
            chkBoxMsAll.setSelected(isMsAll());
            keyListenerList.add(chkBoxMsAll);
            msPanel.add(chkBoxMsAll);

            for (Iterator i = msCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                JCheckBox chkBox = (JCheckBox) msCheck.get(key);
                keyListenerList.add(chkBox);
                msPanel.add(chkBox);
                msPanel.add(new JLabel(" "));
            }

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(msPanel, itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 1, 0, GridBagConstraints.REMAINDER, 1));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));
            delimPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            container.add(delimPanel, mainContainerGBC(0, 3, 1, 1));

            // Ion Mode
            labelPanel = newLabelPanel("Ion Mode", " Ion mode. ", LABEL_SIZE_L, 2);

            JPanel ionPanel = new JPanel();
            ionPanel.setLayout(new BoxLayout(ionPanel, BoxLayout.X_AXIS));

            ButtonGroup ionGroup = new ButtonGroup();
            for (Iterator i = ionRadio.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                JRadioButton rdoBtn = (JRadioButton) ionRadio.get(key);
                keyListenerList.add(rdoBtn);
                ionGroup.add(rdoBtn);
                ionPanel.add(rdoBtn);
            }

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(ionPanel, itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 1, 0, GridBagConstraints.REMAINDER, 1));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));
            delimPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            container.add(delimPanel, mainContainerGBC(0, 4, 1, 1));

            // Precursor m/z
            labelPanel = newLabelPanel("Precursor m/z", " Precursor m/z. ", LABEL_SIZE_L, 2);

            preField = new JTextField(((PRECURSOR < 0) ? "" : String.valueOf(PRECURSOR)), 5);
            preField.setHorizontalAlignment(JTextField.RIGHT);
            keyListenerList.add(preField);

            itemPanel = new JPanel();
            initItemPanel(itemPanel);
            itemPanel.add(wrappTextPanel(preField), itemPanelGBC(0d, 0d, 0, 0, 1, 1));
            itemPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            delimPanel = new JPanel();
            initDelimPanel(delimPanel, true);
            delimPanel.add(labelPanel, delimPanelGBC(0d, 0d, 0, 0, 1, 1));
            delimPanel.add(itemPanel, delimPanelGBC(0d, 0d, 1, 0, 1, 1));
            delimPanel.add(new JPanel(), itemPanelGBC(1d, 0d, 2, 0, GridBagConstraints.REMAINDER, 1));

            container.add(delimPanel, mainContainerGBC(0, 5, 1, 1));

            // 
            final JButton okButton = new JButton("OK");
            keyListenerList.add(okButton);
            final JButton cancelButton = new JButton("Cancel");
            keyListenerList.add(cancelButton);
            JPanel btnPanel = new JPanel();
            btnPanel.add(okButton);
            btnPanel.add(cancelButton);

            container.add(btnPanel, mainContainerGBC(0, 6, 1, 1));

            // All?
            chkBoxInstAll.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (Iterator i = instCheck.keySet().iterator(); i.hasNext();) {
                        String key = (String) i.next();
                        if (chkBoxInstAll.isSelected()) {
                            ((JCheckBox) instCheck.get(key)).setSelected(true);
                        } else {
                            ((JCheckBox) instCheck.get(key)).setSelected(false);
                        }
                    }
                    chkBoxInstDefault.setSelected(isInstDefault());
                }
            });

            // Default?
            chkBoxInstDefault.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (Iterator i = instCheck.keySet().iterator(); i.hasNext();) {
                        String key = (String) i.next();
                        if (chkBoxInstDefault.isSelected()) {
                            // All??????
                            chkBoxInstAll.setSelected(false);
                            if (isDefaultInst(key)) {
                                ((JCheckBox) instCheck.get(key)).setSelected(true);
                            } else {
                                ((JCheckBox) instCheck.get(key)).setSelected(false);
                            }
                        } else {
                            ((JCheckBox) instCheck.get(key)).setSelected(false);
                        }
                    }
                    chkBoxInstAll.setSelected(isInstAll());
                }
            });

            // ?
            for (Iterator i = instCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                ((JCheckBox) instCheck.get(key)).addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        chkBoxInstAll.setSelected(isInstAll());
                        chkBoxInstDefault.setSelected(isInstDefault());
                    }
                });
            }

            // MSAll?
            chkBoxMsAll.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (Iterator i = msCheck.keySet().iterator(); i.hasNext();) {
                        String key = (String) i.next();
                        if (chkBoxMsAll.isSelected()) {
                            ((JCheckBox) msCheck.get(key)).setSelected(true);
                        } else {
                            ((JCheckBox) msCheck.get(key)).setSelected(false);
                        }
                    }
                }
            });

            // MS?
            for (Iterator i = msCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                ((JCheckBox) msCheck.get(key)).addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        chkBoxMsAll.setSelected(isMsAll());
                    }
                });
            }

            // OK
            okButton.addActionListener(new ActionListener() {
                private final Color defColor = okButton.getBackground();

                private void startProc() {
                    // ?
                    okButton.setBackground(Color.PINK);
                    okButton.update(okButton.getGraphics());
                    // ?
                    ParameterSetWindow.this.setCursor(waitCursor);
                }

                private void endProc() {
                    // ?
                    if (!ParameterSetWindow.this.getCursor().equals(Cursor.getDefaultCursor())) {
                        ParameterSetWindow.this.setCursor(Cursor.getDefaultCursor());
                    }
                    // ??
                    okButton.setBackground(defColor);
                }

                public void actionPerformed(ActionEvent e) {

                    startProc();

                    // ?
                    try {
                        tolField.setText(tolField.getText().trim());
                        float num = Float.parseFloat(tolField.getText());
                        if (num < 0) {
                            JOptionPane.showMessageDialog(null,
                                    "[Tolerance]  Value must be an positive numerical value.", "Warning",
                                    JOptionPane.WARNING_MESSAGE);
                            endProc();
                            return;
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "[Tolerance]  Value must be an numerical value.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        endProc();
                        return;
                    }
                    try {
                        cutoffField.setText(cutoffField.getText().trim());
                        int num = Integer.parseInt(cutoffField.getText());
                        if (num < 0) {
                            JOptionPane.showMessageDialog(null,
                                    "[Cutoff Threshold]  Value must be an positive integer.", "Warning",
                                    JOptionPane.WARNING_MESSAGE);
                            endProc();
                            return;
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "[Cutoff Threshold]  Value must be an integer.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        endProc();
                        return;
                    }
                    if (instCheck.size() == 0) {
                        JOptionPane.showMessageDialog(null,
                                "[Instrument Type]  Instrument type is not registered in the database.", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        endProc();
                        return;
                    }
                    if (!isInstCheck()) {
                        JOptionPane.showMessageDialog(null, "[Instrument Type]  Select one or more checkbox.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        endProc();
                        return;
                    }
                    if (msCheck.size() == 0) {
                        JOptionPane.showMessageDialog(null, "[MS Type]  MS type is not registered in the database.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        endProc();
                        return;
                    }
                    if (!isMsCheck()) {
                        JOptionPane.showMessageDialog(null, "[MS Type]  Select one or more checkbox.", "Warning",
                                JOptionPane.WARNING_MESSAGE);
                        endProc();
                        return;
                    }
                    try {
                        preField.setText(preField.getText().trim());
                        if (!preField.getText().equals("")) {
                            int num = Integer.parseInt(preField.getText());
                            if (num < 1) {
                                JOptionPane.showMessageDialog(null,
                                        "[Precursor m/z]  Value must be an integer of 1 or more.", "Warning",
                                        JOptionPane.WARNING_MESSAGE);
                                endProc();
                                return;
                            }
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null,
                                "[Precursor m/z]  Value must be an integer of 1 or more.", "Warning",
                                JOptionPane.WARNING_MESSAGE);
                        endProc();
                        return;
                    }

                    // ???????
                    if (isPreChange() || isTolChange() || isCutoffChange() || isInstChange() || isMsChange()
                            || isIonChange()) {

                        preChange(true);
                        tolChange(true);
                        cutoffChange(true);
                        instChange(true);
                        msChange(true);
                        ionChange(true);

                        // ????
                        resultPlot.setSpectrumInfo("", "", "", "", false);
                        switch (queryTabPane.getSelectedIndex()) {
                        case TAB_ORDER_DB: // DB?
                            updateSelectQueryTable(queryDbTable);
                            break;
                        case TAB_ORDER_FILE: // FILE?
                            updateSelectQueryTable(queryFileTable);
                            break;
                        }
                    }

                    endProc();

                    dispose();
                    isSubWindow = false;
                }
            });

            // Cancel
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // ?
                    preChange(false);
                    tolChange(false);
                    cutoffChange(false);
                    instChange(false);
                    msChange(false);
                    ionChange(false);

                    dispose();
                    isSubWindow = false;
                }
            });

            // 
            for (int i = 0; i < keyListenerList.size(); i++) {
                keyListenerList.get(i).addKeyListener(new KeyAdapter() {
                    public void keyReleased(KeyEvent e) {
                        // Esc
                        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                            // ?
                            preChange(false);
                            tolChange(false);
                            cutoffChange(false);
                            instChange(false);
                            msChange(false);
                            ionChange(false);

                            dispose();
                            isSubWindow = false;
                        }
                    }
                });
            }
            //         setTitle("Search Parameter Setting");
            pack();
            //         Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            //         setLocation((int)(d.getWidth() / 2 - getWidth() / 2),
            //               (int)(d.getHeight() / 2 - getHeight() / 2));
            setLocation();
            setVisible(true);

            // 
            addWindowListener(new WindowAdapter() {
                public void windowOpened(WindowEvent e) {
                    isSubWindow = true;
                }

                public void windowClosing(WindowEvent e) {
                    cancelButton.doClick();
                }
            });
        }

        /**
         * Tolerance?
         * Tolerance???????true??
         * @return 
         */
        private boolean isTolChange() {

            if (Float.parseFloat(tolField.getText()) != TOLERANCE) {
                return true;
            } else if (isTolUnit1 != tolUnit1.isSelected() || isTolUnit2 != tolUnit2.isSelected()) {
                return true;
            }
            return false;
        }

        /**
         * Tolerance
         * Tolerance?????????
         * @param isChange 
         */
        private void tolChange(boolean isChange) {

            if (isChange) {

                // Cookie
                //            ArrayList<String> valueList = new ArrayList<String>();

                TOLERANCE = Float.parseFloat(tolField.getText());
                SystemProperties.setDefaultTolerance(TOLERANCE);

                //            valueList.add(String.valueOf(TOLERANCE));

                isTolUnit1 = tolUnit1.isSelected();
                isTolUnit2 = tolUnit2.isSelected();
                if (tolUnit2.isSelected()) {
                    SystemProperties.setDefaultToleranceUnit(tolUnit2.getText());
                    //               valueList.add(tolUnit2.getText());
                } else {
                    SystemProperties.setDefaultToleranceUnit(tolUnit1.getText());
                    //               valueList.add(tolUnit1.getText());
                }

                // ToleranceCookie?
                //            cm.setCookie(COOKIE_TOL, valueList);
            } else {
                tolUnit1.setSelected(isTolUnit1);
                tolUnit2.setSelected(isTolUnit2);
            }
        }

        /**
         * Cutoff Threshold?
         * Cutoff Threshold???????true??
         * @return 
         */
        private boolean isCutoffChange() {

            if (Integer.parseInt(cutoffField.getText()) != CUTOFF_THRESHOLD) {
                return true;
            }
            return false;
        }

        /**
         * Cutoff Threshold
         * Cutoff Threshold?????????
         * @param isChange 
         */
        private void cutoffChange(boolean isChange) {

            if (isChange) {

                // Cookie
                //            ArrayList<String> valueList = new ArrayList<String>();

                CUTOFF_THRESHOLD = Integer.parseInt(cutoffField.getText());
                SystemProperties.setDefaultCutoffThreshold(CUTOFF_THRESHOLD);

                //            valueList.add(String.valueOf(CUTOFF_THRESHOLD));

                //            // Cutoff ThresholdCookie?
                //            cm.setCookie(COOKIE_CUTOFF, valueList);
            }
        }

        /**
         * ??All
         * ?All????
         * @return All?
         */
        private boolean isInstAll() {

            if (instCheck.size() == 0) {
                return false;
            }
            for (Iterator j = instCheck.keySet().iterator(); j.hasNext();) {
                String key = (String) j.next();

                if (!((JCheckBox) instCheck.get(key)).isSelected()) {
                    return false;
                }
            }
            return true;
        }

        /**
         * ??Default
         * ?Default???? 
         * @return Default?
         */
        private boolean isInstDefault() {

            if (instCheck.size() == 0) {
                return false;
            }
            for (Iterator j = instCheck.keySet().iterator(); j.hasNext();) {
                String key = (String) j.next();
                if (isDefaultInst(key)) { // ??
                    if (!((JCheckBox) instCheck.get(key)).isSelected()) {
                        return false;
                    }
                } else {
                    if (((JCheckBox) instCheck.get(key)).isSelected()) {
                        return false;
                    }
                }
            }
            return true;
        }

        /**
         * ??
         * ?1?????????true??
         * @return ??
         */
        private boolean isInstCheck() {

            if (instCheck.size() == 0) {
                return false;
            }
            for (Iterator j = instCheck.keySet().iterator(); j.hasNext();) {
                String key = (String) j.next();
                if (((JCheckBox) instCheck.get(key)).isSelected()) {
                    return true;
                }
            }
            return false;
        }

        /**
         * ??
         * ???1????????true??
         * @return 
         */
        private boolean isInstChange() {

            if (isInstCheck.size() == 0) {
                return false;
            }
            for (Iterator i = isInstCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                boolean before = (boolean) isInstCheck.get(key);
                boolean after = ((JCheckBox) instCheck.get(key)).isSelected();
                if (before != after) {
                    return true;
                }
            }
            return false;
        }

        /**
         * ?
         * ???????????
         * @param isChange 
         */
        private void instChange(boolean isChange) {

            // Cookie
            ArrayList<String> valueList = new ArrayList<String>();

            if (isInstCheck.size() == 0) {
                return;
            }
            for (Iterator i = isInstCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                boolean before = (boolean) isInstCheck.get(key);
                boolean after = ((JCheckBox) instCheck.get(key)).isSelected();
                if (before != after) {
                    if (isChange) {
                        isInstCheck.put(key, after);
                    } else {
                        ((JCheckBox) instCheck.get(key)).setSelected(before);
                    }
                }
                if (((JCheckBox) instCheck.get(key)).isSelected()) {
                    valueList.add(key);
                }
            }
            // ?Cookie?
            if (isChange) {
                SystemProperties.setDefaultInstanceTypeList(valueList);
                //            cm.setCookie(COOKIE_INST, valueList);
            }
        }

        /**
         * MS??All
         * MS?All????
         * @return All?
         */
        private boolean isMsAll() {

            if (msCheck.size() == 0) {
                return false;
            }
            for (Iterator j = msCheck.keySet().iterator(); j.hasNext();) {
                String key = (String) j.next();
                if (!((JCheckBox) msCheck.get(key)).isSelected()) {
                    return false;
                }
            }
            return true;
        }

        /**
         * MS??
         * MS?1?????????true??
         * @return ??
         */
        private boolean isMsCheck() {

            if (msCheck.size() == 0) {
                return false;
            }
            for (Iterator j = msCheck.keySet().iterator(); j.hasNext();) {
                String key = (String) j.next();
                if (((JCheckBox) msCheck.get(key)).isSelected()) {
                    return true;
                }
            }
            return false;
        }

        /**
         * MS??
         * MS???1????????true??
         * @return 
         */
        private boolean isMsChange() {

            if (isMsCheck.size() == 0) {
                return false;
            }
            for (Iterator i = isMsCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                boolean before = (boolean) isMsCheck.get(key);
                boolean after = ((JCheckBox) msCheck.get(key)).isSelected();
                if (before != after) {
                    return true;
                }
            }
            return false;
        }

        /**
         * MS?
         * ???????????
         * @param isChange 
         */
        private void msChange(boolean isChange) {

            // Cookie
            ArrayList<String> valueList = new ArrayList<String>();

            if (isMsCheck.size() == 0) {
                return;
            }
            for (Iterator i = isMsCheck.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();
                boolean before = (boolean) isMsCheck.get(key);
                boolean after = ((JCheckBox) msCheck.get(key)).isSelected();
                if (before != after) {
                    if (isChange) {
                        isMsCheck.put(key, after);
                    } else {
                        ((JCheckBox) msCheck.get(key)).setSelected(before);
                    }
                }
                if (((JCheckBox) msCheck.get(key)).isSelected()) {
                    valueList.add(key);
                }
            }
            // MS?Cookie?
            if (isChange) {
                SystemProperties.setDefaultMsList(valueList);
                //            cm.setCookie(COOKIE_MS, valueList);
            }
        }

        /**
         * ??
         * ????????true??
         * @return 
         */
        private boolean isIonChange() {

            for (Iterator i = isIonRadio.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                boolean before = (boolean) isIonRadio.get(key);
                boolean after = ((JRadioButton) ionRadio.get(key)).isSelected();

                if (before != after) {
                    return true;
                }
            }
            return false;
        }

        /**
         * ?
         * ??????????
         * @param isChange 
         */
        private void ionChange(boolean isChange) {

            // Cookie
            ArrayList<String> valueList = new ArrayList<String>();

            for (Iterator i = isIonRadio.keySet().iterator(); i.hasNext();) {
                String key = (String) i.next();

                boolean before = (boolean) isIonRadio.get(key);
                boolean after = ((JRadioButton) ionRadio.get(key)).isSelected();

                if (before != after) {
                    if (isChange) {
                        isIonRadio.put(key, after);
                    } else {
                        ((JRadioButton) ionRadio.get(key)).setSelected(before);
                    }
                }
                if (((JRadioButton) ionRadio.get(key)).isSelected()) {
                    valueList.add(key);
                }
            }
            // ?Cookie?
            if (isChange) {
                SystemProperties.setDefaultIonList(valueList);
                //            cm.setCookie(COOKIE_ION, valueList);
            }
        }

        /**
         * Precursor m/z?
         * Precursor m/z???????true??
         * @return 
         */
        private boolean isPreChange() {

            if (preField.getText().equals("")) {
                if (PRECURSOR != -1) {
                    return true;
                }
            } else if (Integer.parseInt(preField.getText()) != PRECURSOR) {
                return true;
            }
            return false;
        }

        /**
         * Precursor m/z
         * Precursor m/z?????????
         * @param isChange 
         */
        private void preChange(boolean isChange) {

            if (isChange) {

                //            // Cookie
                //            ArrayList<String> valueList = new ArrayList<String>();

                if (preField.getText().equals("")) {
                    PRECURSOR = -1;
                } else {
                    PRECURSOR = Integer.parseInt(preField.getText());
                }
                //            valueList.add(String.valueOf(PRECURSOR));

                //            // Precursor m/zCookie?
                //            cm.setCookie(COOKIE_PRE, valueList);
            }
        }

        /**
         * ??
         * @param c 
         */
        private void initMainContainer(Container c) {
            c.setLayout(new GridBagLayout());
        }

        /**
         * 
         * @param x ??
         * @param y ??
         * @param w ??1?
         * @param h ??1?
         * @return 
         */
        private GridBagConstraints mainContainerGBC(int x, int y, int w, int h) {

            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            gbc.weightx = 1.0d;
            gbc.weighty = 1.0d;
            gbc.insets = new Insets(15, 15, 0, 15);

            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = w;
            gbc.gridheight = h;

            return gbc;
        }

        /**
         * ?????
         * 
         * @param p
         * @param isBorder
         * @return ??
         */
        private void initDelimPanel(JPanel p, boolean isBorder) {

            p.setLayout(new GridBagLayout());

            if (isBorder) {
                Border border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
                        new EmptyBorder(3, 3, 3, 3));
                p.setBorder(border);
            }
        }

        /**
         * ????
         * 
         * @parma wx ??
         * @parma wy ??
         * @param x ??
         * @param y ??
         * @param w ??1?
         * @param h ??1?
         * @return 
         */
        private GridBagConstraints delimPanelGBC(double wx, double wy, int x, int y, int w, int h) {

            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            gbc.weightx = wx;
            gbc.weighty = wy;
            gbc.insets = new Insets(2, 2, 2, 2);

            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = w;
            gbc.gridheight = h;

            return gbc;
        }

        /**
         * ??
         * 
         * JLabel???add?????????????
         * ?JPanel?????
         * ????????????
         * 
         * @param label HTML??
         * @param tooltip ?HTML??
         * @param size 
         * @param labelIndent ??
         * @return ???
         */
        private JPanel newLabelPanel(String label, String tooltip, int size, int labelIndent) {
            // ?
            for (int i = 0; i < labelIndent; i++) {
                label = " " + label;
            }
            JLabel l = new JLabel(label);

            switch (size) {
            case LABEL_SIZE_L:
                l.setPreferredSize(new Dimension(110, 20));
                l.setMinimumSize(new Dimension(110, 20));
                break;
            case LABEL_SIZE_M:
                l.setPreferredSize(new Dimension(85, 20));
                l.setMinimumSize(new Dimension(85, 20));
                break;
            case LABEL_SIZE_S:
                l.setPreferredSize(new Dimension(45, 20));
                l.setMinimumSize(new Dimension(45, 20));
                break;
            default:
                break;
            }

            if (tooltip != null) {
                l.setToolTipText(tooltip);
            }

            // ?
            JPanel p = new JPanel();
            p.setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 0.0d;
            gbc.weighty = 0.0d;
            gbc.insets = new Insets(2, 2, 2, 2);

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;

            p.add(l, gbc);

            return p;
        }

        /**
         * 
         * 
         * JTextFieldadd???????????
         * 
         * @return ???
         */
        private JPanel wrappTextPanel(JTextField t) {

            // ?
            JPanel p = new JPanel();
            p.setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 0.0d;
            gbc.weighty = 0.0d;
            gbc.insets = new Insets(2, 2, 2, 2);

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;

            p.add(t, gbc);

            return p;
        }

        /**
         * ???
         * @return ?
         */
        private void initItemPanel(JPanel p) {
            p.setLayout(new GridBagLayout());
        }

        /**
         * ??
         * @parma wx ??
         * @parma wy ??
         * @param x ??
         * @param y ??
         * @param w ??1?
         * @param h ??1?
         * @return 
         */
        private GridBagConstraints itemPanelGBC(double wx, double wy, int x, int y, int w, int h) {

            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            gbc.weightx = wx;
            gbc.weighty = wy;
            gbc.insets = new Insets(2, 2, 2, 2);

            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = w;
            gbc.gridheight = h;

            return gbc;
        }
    }

    /**
     * File?
     * SerarchPage?
     */
    class LmFileListener implements ListSelectionListener {

        /**
         * ??
         * @see javax.swing.event.ListSelectionListener#valueChanged(java.swing.event.ListSelectionEvent)
         */
        public void valueChanged(ListSelectionEvent le) {

            if (le.getValueIsAdjusting()) {
                return;
            }

            final int selRow = queryFileTable.getSelectedRow();
            if (selRow < 0) {
                // CompareView?
                queryPlot.clear();
                compPlot.clear();
                resultPlot.clear();
                queryPlot.setPeaks(null, 0);
                compPlot.setPeaks(null, 1);
                resultPlot.setPeaks(null, 0);

                // PackageView?
                pkgView.initAllRecInfo();

                DefaultTableModel dm = (DefaultTableModel) resultSorter.getTableModel();
                dm.setRowCount(0);
                hitLabel.setText(" ");
                return;
            }

            // ?
            SearchPage.this.setCursor(waitCursor);

            // PackageView
            int noCol = queryFileTable.getColumnModel().getColumnIndex(COL_LABEL_NO);
            int nameCol = queryFileTable.getColumnModel().getColumnIndex(COL_LABEL_NAME);
            int idCol = queryFileTable.getColumnModel().getColumnIndex(COL_LABEL_ID);

            // 
            String[] peaks = userDataList[selRow].getPeaks();

            PackageRecData recData = new PackageRecData();

            // ==  ===
            recData.setQueryRecord(true);

            // === ? ===
            recData.setIntegRecord(false);

            // === ID ===
            recData.setId((String) queryFileTable.getValueAt(selRow, idCol));

            // ===  ===
            recData.setScore(" -");

            // ===  ===
            recData.setSite("");

            // === ??? ===
            recData.setName((String) queryFileTable.getValueAt(selRow, nameCol));

            // ===  ===
            recData.setPrecursor("");

            // ===  ===
            int num = peaks.length;
            if (num == 1) {
                if (peaks[0].split("\t")[0].equals("0") && peaks[0].split("\t")[1].equals("0")) {
                    num = 0;
                }
            }
            recData.setPeakNum(num);

            for (int i = 0; i < recData.getPeakNum(); i++) {
                // === m/z ===
                recData.setMz(i, peaks[i].split("\t")[0]);

                // ===  ===
                recData.setIntensity(i, peaks[i].split("\t")[1]);
            }

            // ===  ===
            recData.setPeakColorType(PackageRecData.COLOR_TYPE_BLACK);

            // 
            pkgView.addQueryRecInfo(recData);
            pkgView.addRecInfoAfter(true, recData.getId(), PackageSpecData.SORT_KEY_NONE);

            // DB
            String name = (String) queryFileTable.getValueAt(selRow, nameCol);
            String key = String.valueOf(queryFileTable.getValueAt(selRow, noCol));
            searchDb(userDataList[selRow].getPeaks(), "", name, key);
        }
    }

    /**
     * Result?
     * SerarchPage?
     */
    class LmResultListener implements ListSelectionListener {

        /**
         * ??
         * @see javax.swing.event.ListSelectionListener#valueChanged(java.swing.event.ListSelectionEvent)
         */
        public void valueChanged(ListSelectionEvent le) {

            if (le.getValueIsAdjusting()) {
                return;
            }

            int[] selRows = resultTable.getSelectedRows();
            if (selRows.length < 1) {
                // CompareView?
                resultPlot.clear();
                compPlot.setPeaks(null, 1);
                resultPlot.setPeaks(null, 0);
                setAllPlotAreaRange();

                // PackageView?
                pkgView.initResultRecInfo();
                return;
            }

            // ?
            SearchPage.this.setCursor(waitCursor);

            int idCol = resultTable.getColumnModel().getColumnIndex(COL_LABEL_ID);
            int nameCol = resultTable.getColumnModel().getColumnIndex(COL_LABEL_NAME);
            int siteNameCol = resultTable.getColumnModel().getColumnIndex(COL_LABEL_CONTRIBUTOR);
            int scoreCol = resultTable.getColumnModel().getColumnIndex(COL_LABEL_SCORE);

            String typeName = MassBankCommon.CGI_TBL[MassBankCommon.CGI_TBL_NUM_TYPE][MassBankCommon.CGI_TBL_TYPE_GSDATA];
            String id;
            String name;
            boolean relation;
            int ion;
            String score;
            String siteName;
            String site = "0";
            PackageRecData recData = null;

            //         if (isIonRadio.get("Posi")) {
            if (isIonRadio.get(IonMode.POSITIVE.getKey())) {
                ion = 1;
                //         } else if (isIonRadio.get("Nega")) {
            } else if (isIonRadio.get(IonMode.NEGATIVE.getKey())) {
                ion = -1;
            } else {
                ion = 0;
            }

            if (isDispSelected) {

                // Compare View?
                if (selRows.length > 1) {
                    // 2???????
                    resultPlot.clear();
                    compPlot.setPeaks(null, 1);
                    resultPlot.setPeaks(null, 0);
                    setAllPlotAreaRange();
                }
                if (selRows.length > MAX_DISPLAY_NUM) {
                    JOptionPane.showMessageDialog(null,
                            "Cannot display more than " + MAX_DISPLAY_NUM + " spectra in Package View.", "Warning",
                            JOptionPane.WARNING_MESSAGE);
                    SearchPage.this.setCursor(Cursor.getDefaultCursor());
                    return;
                }

                // PackageView
                boolean recChangeFlag = true;
                PeakData peak = null;
                for (int i = 0; i < selRows.length; i++) {

                    id = (String) resultTable.getValueAt(selRows[i], idCol);
                    name = (String) resultTable.getValueAt(selRows[i], nameCol);
                    relation = false;
                    score = String.valueOf(resultTable.getValueAt(selRows[i], scoreCol));
                    siteName = (String) resultTable.getValueAt(selRows[i], siteNameCol);
                    //               for (int j=0; j<siteNameList.length; j++) {
                    //                  if (siteName.equals(siteNameList[j])) {
                    //                     site = Integer.toString(j);
                    //                     break;
                    //                  }
                    //               }

                    //               String reqUrl = baseUrl + "jsp/"
                    //                     + MassBankCommon.DISPATCHER_NAME + "?type="
                    //                     + typeName + "&id=" + id + "&site=" + site + "&relation=" + relation + "&ion=" + ion;
                    //                 LOGGER.info("not calling... " + reqUrl);
                    String line = "";
                    String findStr;
                    //               try {
                    //                  URL url = new URL( reqUrl );
                    //                  URLConnection con = url.openConnection();
                    //                  
                    //                  // ??
                    //                  BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) );
                    //                  
                    //                  // ??
                    //                  String result;
                    //                  while ( (result = in.readLine()) != null ) {
                    //                     if ( !result.equals("") ) {      // ???
                    //                        line = result;
                    //                        LOGGER.info(line);
                    //                        break;
                    //                     }
                    //                  }
                    //                  in.close();
                    //               }
                    //               catch (IOException iex) {
                    //                  iex.printStackTrace();
                    //                  SearchPage.this.setCursor(Cursor.getDefaultCursor());
                    //               }
                    try {
                        DbAccessor.createConnection();
                        SpectrumLogic spectrumLogic = new SpectrumLogic();
                        line = spectrumLogic.getSpectrumData(id, ion, relation);
                        DbAccessor.closeConnection();
                        //                    line = OldDbAccessor.getSpectrumData(id);
                    } catch (SQLException e) {
                        LOGGER.error(e.getMessage(), e);
                        SearchPage.this.setCursor(Cursor.getDefaultCursor());
                    }
                    //                  LOGGER.info("result... " + line);
                    recData = new PackageRecData();

                    // === ??? ===
                    findStr = "name=";
                    recData.setName(line, findStr);

                    // ===  ===
                    findStr = "precursor=";
                    recData.setPrecursor(line, findStr);

                    // === ID ===
                    findStr = "id=";
                    recData.setId(line, findStr);

                    // ===  ===
                    recData.setResultRecord(true);

                    // === ? ===
                    recData.setIntegRecord(recData.getName());

                    // ===  ===
                    recData.setScore(score);

                    // ===  ===
                    recData.setSite(site);

                    // ????(m/z?)???
                    // ???
                    if (line.indexOf("::") > 0) {
                        line = line.substring(0, line.indexOf("::"));
                    }
                    String[] tmpPeak = line.split("\t\t");

                    // ===  ===
                    int num = tmpPeak.length;
                    if (num == 1) {
                        if (tmpPeak[0].split("\t")[0].equals("0") && tmpPeak[0].split("\t")[1].equals("0")) {
                            num = 0;
                        }
                    }
                    recData.setPeakNum(num);

                    for (int j = 0; j < recData.getPeakNum(); j++) {
                        // === m/z ===
                        recData.setMz(j, tmpPeak[j].split("\t")[0]);

                        // ===  ===
                        recData.setIntensity(j, tmpPeak[j].split("\t")[1]);
                    }

                    // ===  ===
                    recData.setPeakColorType(PackageRecData.COLOR_TYPE_BLACK);

                    // 
                    pkgView.addResultRecInfo(recData, recChangeFlag);
                    recChangeFlag = false;

                    // Compare View?
                    if (selRows.length == 1) {
                        peak = new PeakData(tmpPeak);
                        resultPlot.clear();
                        resultPlot.setPeaks(peak, 0);
                        resultPlot.setSpectrumInfo(name, id, recData.getPrecursor(), PeakPanel.SP_TYPE_RESULT,
                                false);
                        compPlot.setPeaks(peak, 1);
                        setAllPlotAreaRange();
                        compPlot.setTolerance(String.valueOf(TOLERANCE), tolUnit1.isSelected());
                    }
                }

                pkgView.setTolerance(String.valueOf(TOLERANCE), tolUnit1.isSelected());
                pkgView.addRecInfoAfter(
                        false, (String) resultTable
                                .getValueAt(resultTable.getSelectionModel().getLeadSelectionIndex(), idCol),
                        PackageSpecData.SORT_KEY_SCORE);
            } else if (isDispRelated) {
                id = (String) resultTable.getValueAt(selRows[0], idCol);
                name = (String) resultTable.getValueAt(selRows[0], nameCol);
                relation = true;
                siteName = (String) resultTable.getValueAt(selRows[0], siteNameCol);
                //            for (int i = 0; i < siteNameList.length; i++) {
                //               if (siteName.equals(siteNameList[i])) {
                //                  site = Integer.toString(i);
                //                  break;
                //               }
                //            }

                // TODO
                String reqUrl = Constant.ExternalUrl.SHOW_DISPATCH_PAGE;
                //            String reqUrl = baseUrl + "jsp/"
                //                  + MassBankCommon.DISPATCHER_NAME + "?type="
                //                  + typeName + "&id=" + id + "&site=" + site + "&relation=" + relation + "&ion=" + ion;
                LOGGER.info(reqUrl);
                String precursor = "";
                PeakData peak = null;
                try {
                    URL url = new URL(reqUrl);
                    URLConnection con = url.openConnection();
                    String line = "";
                    String findStr;
                    boolean recChangeFlag = true;
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    // PackageView
                    while ((line = in.readLine()) != null) {
                        if (line.equals("")) { // ???
                            continue;
                        }
                        LOGGER.info("relation is " + relation + " " + line);
                        recData = new PackageRecData();

                        // === ??? ===
                        findStr = "name=";
                        recData.setName(line, findStr);

                        // ===  ===
                        findStr = "precursor=";
                        recData.setPrecursor(line, findStr);

                        // === ID ===
                        findStr = "id=";
                        recData.setId(line, findStr);

                        // === ? ===
                        recData.setIntegRecord(recData.getName());

                        // ===  ===
                        recData.setScore("");

                        // ===  ===
                        recData.setSite(site);

                        // ????(m/z?)???
                        // ???
                        if (line.indexOf("::") > 0) {
                            line = line.substring(0, line.indexOf("::"));
                        }
                        String[] tmpPeak = line.split("\t\t");

                        // ===  ===
                        int num = tmpPeak.length;
                        if (num == 1) {
                            if (tmpPeak[0].split("\t")[0].equals("0") && tmpPeak[0].split("\t")[1].equals("0")) {
                                num = 0;
                            }
                        }
                        recData.setPeakNum(num);

                        for (int j = 0; j < recData.getPeakNum(); j++) {
                            // === m/z ===
                            recData.setMz(j, tmpPeak[j].split("\t")[0]);

                            // ===  ===
                            recData.setIntensity(j, tmpPeak[j].split("\t")[1]);
                        }

                        // ===  ===
                        recData.setPeakColorType(PackageRecData.COLOR_TYPE_BLACK);

                        // 
                        pkgView.addResultRecInfo(recData, recChangeFlag);
                        recChangeFlag = false;

                        // Compare View?
                        if (id.equals(recData.getId())) {
                            peak = new PeakData(tmpPeak);
                            precursor = recData.getPrecursor();
                        }
                    }
                    in.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    SearchPage.this.setCursor(Cursor.getDefaultCursor());
                }

                pkgView.setTolerance(String.valueOf(TOLERANCE), tolUnit1.isSelected());
                pkgView.addRecInfoAfter(false, id, PackageSpecData.SORT_KEY_NAME);

                resultPlot.clear();
                resultPlot.setPeaks(peak, 0);
                resultPlot.setSpectrumInfo(name, id, precursor, PeakPanel.SP_TYPE_RESULT, false);
                compPlot.setPeaks(peak, 1);

                setAllPlotAreaRange();
                compPlot.setTolerance(String.valueOf(TOLERANCE), tolUnit1.isSelected());
            }

            // ???????
            id = recData.getId();
            site = recData.getSite();
            String temp = recData.getName();
            String[] items = temp.split(";");
            name = URLEncoder.encode(items[0]);
            //         String getUrl = baseUrl + "jsp/GetCompoudInfo.jsp?name=" + name + "&site=" + site + "&id=" + id;
            //         LOGGER.info(getUrl);
            String gifMFileName = "";
            String gifSFileName = "";
            String formula = "";
            String emass = "";
            try {
                //            URL url = new URL(getUrl);
                //            URLConnection con = url.openConnection();
                //            BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) );
                //            String line = "";
                //            while ( (line = in.readLine()) != null ) {
                //               if ( line.indexOf("GIF:") >= 0 ) {
                //                  gifMFileName = line.replace("GIF:", "");
                //               }
                //               else if ( line.indexOf("GIF_SMALL:") >= 0 ) {
                //                  gifSFileName = line.replace("GIF_SMALL:", "");
                //               }
                //               else if ( line.indexOf("FORMULA:") >= 0 ) {
                //                  formula = line.replace("FORMULA:", "");
                //               }
                //               else if ( line.indexOf("EXACT_MASS:") >= 0 ) {
                //                  emass = line.replace("EXACT_MASS:", "");
                //               }
                //            }
                DbAccessor.createConnection();
                CompoundLogic compoundLogic = new CompoundLogic();
                List<String> infoList = compoundLogic.getInfo(id, name);
                DbAccessor.closeConnection();
                for (String line : infoList) {
                    if (line.indexOf("GIF:") >= 0) {
                        gifMFileName = line.replace("GIF:", "");
                    } else if (line.indexOf("GIF_SMALL:") >= 0) {
                        gifSFileName = line.replace("GIF_SMALL:", "");
                    } else if (line.indexOf("FORMULA:") >= 0) {
                        formula = line.replace("FORMULA:", "");
                    } else if (line.indexOf("EXACT_MASS:") >= 0) {
                        emass = line.replace("EXACT_MASS:", "");
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            resultPlot.loadStructGif(gifMFileName, gifSFileName);
            resultPlot.setCompoundInfo(formula, emass);

            SearchPage.this.setCursor(Cursor.getDefaultCursor());
        }
    }

    /**
     * DB?
     * SerarchPage?
     */
    class LmQueryDbListener implements ListSelectionListener {

        /**
         * ??
         * @see javax.swing.event.ListSelectionListener#valueChanged(java.swing.event.ListSelectionEvent)
         */
        public void valueChanged(ListSelectionEvent le) {

            if (le.getValueIsAdjusting()) {
                return;
            }

            final int selRow = queryDbTable.getSelectedRow();
            if (selRow < 0) {
                // CompareView?
                queryPlot.clear();
                compPlot.clear();
                resultPlot.clear();
                queryPlot.setPeaks(null, 0);
                compPlot.setPeaks(null, 1);
                resultPlot.setPeaks(null, 0);

                // PackageView?
                pkgView.initAllRecInfo();

                DefaultTableModel dm = (DefaultTableModel) resultSorter.getTableModel();
                dm.setRowCount(0);
                hitLabel.setText(" ");
                return;
            }

            // ?
            SearchPage.this.setCursor(waitCursor);

            int idCol = queryDbTable.getColumnModel().getColumnIndex(COL_LABEL_ID);
            int nameCol = queryDbTable.getColumnModel().getColumnIndex(COL_LABEL_NAME);

            String id = (String) queryDbTable.getValueAt(selRow, idCol);
            String site = guiDbTableRowMap.get(id).getContributor();

            // PackageView
            PackageRecData recData = new PackageRecData();

            // ==  ===
            recData.setQueryRecord(true);

            // === ID ===
            recData.setId(id);

            // ===  ===
            recData.setScore(" -");

            // ===  ===
            recData.setSite(site);

            //         String typeName = MassBankCommon.CGI_TBL[MassBankCommon.CGI_TBL_NUM_TYPE][MassBankCommon.CGI_TBL_TYPE_GSDATA];
            //         String reqUrl = baseUrl + "jsp/" + MassBankCommon.DISPATCHER_NAME
            //               + "?type=" + typeName + "&id=" + id + "&site=" + site + "&relation=false";
            //         
            //           LOGGER.info("not calling.. "+reqUrl);

            String line = "";
            String findStr;
            //         try {
            //            URL url = new URL( reqUrl );
            //            URLConnection con = url.openConnection();
            //            
            //            // ??
            //            BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) );
            //            
            //            // ??
            //            String result;
            //            while ( (result = in.readLine()) != null ) {
            //               // ???
            //               if ( !result.equals("") ) {
            //                  line = result;
            //                  break;
            //               }
            //            }
            //            in.close();
            //         }
            //         catch (IOException iex) {
            //         }
            try {
                DbAccessor.createConnection();
                SpectrumLogic spectrumLogic = new SpectrumLogic();
                line = spectrumLogic.getChildInfo(id);
                DbAccessor.closeConnection();
            } catch (SQLException e) {
                LOGGER.error(e.getMessage(), e);
                SearchPage.this.setCursor(Cursor.getDefaultCursor());
            }
            //             LOGGER.info(line);
            // === ??? ===
            findStr = "name=";
            recData.setName(line, findStr);

            // === ? ===
            recData.setIntegRecord(recData.getName());

            // ===  ===
            findStr = "precursor=";
            recData.setPrecursor(line, findStr);

            // ????(m/z?)???
            // ???
            if (line.indexOf("::") > 0) {
                line = line.substring(0, line.indexOf("::"));
            }
            String[] tmpPeak = line.split("\t\t");

            // ===  ===
            int num = tmpPeak.length;
            if (num == 1) {
                if (tmpPeak[0].split("\t")[0].equals("0") && tmpPeak[0].split("\t")[1].equals("0")) {
                    num = 0;
                }
            }
            recData.setPeakNum(num);

            for (int i = 0; i < recData.getPeakNum(); i++) {
                // === m/z ===
                recData.setMz(i, tmpPeak[i].split("\t")[0]);

                // ===  ===
                recData.setIntensity(i, tmpPeak[i].split("\t")[1]);
            }

            // ===  ===
            recData.setPeakColorType(PackageRecData.COLOR_TYPE_BLACK);

            // 
            pkgView.addQueryRecInfo(recData);
            pkgView.addRecInfoAfter(true, id, PackageSpecData.SORT_KEY_NONE);

            // DB
            String name = (String) queryDbTable.getValueAt(selRow, nameCol);
            String key = (String) queryDbTable.getValueAt(selRow, idCol);
            searchDb(tmpPeak, recData.getPrecursor(), name, key);
        }
    }

    /**
     * 
     * SerarchPage?
     */
    class TblMouseListener extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            // ??
            if (SwingUtilities.isLeftMouseButton(e)) {

                JTable tbl = (JTable) e.getSource();

                if (e.getClickCount() == 2 && !tbl.equals(queryFileTable)) {
                    showRecordPage(tbl);
                } else if (e.getClickCount() == 1) {

                    if (e.isShiftDown() || e.isControlDown()) {
                        return;
                    }

                    int selRow[] = tbl.getSelectedRows();
                    int idCol = tbl.getColumnModel().getColumnIndex(COL_LABEL_ID);

                    // Package View ???
                    String id = (String) tbl.getValueAt(selRow[0], idCol);
                    if (tbl.equals(resultTable)) {
                        pkgView.setTblSelection(false, id);
                    } else {
                        pkgView.setTblSelection(true, id);
                    }
                }
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            super.mouseReleased(e);

            // ???
            if (SwingUtilities.isRightMouseButton(e)) {

                recListPopup(e);
            }
        }
    }

    /**
     * 
     * SearchPage?
     */
    class PaneMouseListener extends MouseAdapter {

        @Override
        public void mouseReleased(MouseEvent e) {
            super.mouseReleased(e);

            // ???
            if (SwingUtilities.isRightMouseButton(e)) {
                recListPopup(e);
            }
        }
    }

    /**
     * Search Name
     * SerarchPage?
     */
    class BtnSearchNameListener implements ActionListener {

        /**
         * 
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {

            String inputStr = (String) JOptionPane.showInputDialog(null, "Please input the Name.", "Search Name",
                    JOptionPane.PLAIN_MESSAGE, null, null, saveSearchName);

            // ??Esc
            if (inputStr == null) {
                return;
            }

            String searchName = inputStr.trim();
            // ?
            JButton btn = btnName;
            Color defColor = btn.getBackground();
            btn.setBackground(Color.PINK);
            btn.update(btn.getGraphics());

            // ?
            SearchPage.this.setCursor(waitCursor);

            // ?
            queryPlot.clear();
            compPlot.clear();
            resultPlot.clear();
            queryPlot.setPeaks(null, 0);
            compPlot.setPeaks(null, 1);
            resultPlot.setPeaks(null, 0);

            // PackageView?
            pkgView.initAllRecInfo();

            // DB Hit?
            if (resultTabPane.getTabCount() > 0) {
                resultTabPane.setSelectedIndex(0);
            }
            DefaultTableModel dm1 = (DefaultTableModel) resultSorter.getTableModel();
            dm1.setRowCount(0);
            hitLabel.setText(" ");

            if (StringUtils.isBlank(searchName)) {
                // DB?
                DefaultTableModel dataModel = (DefaultTableModel) querySorter.getTableModel();
                dataModel.setRowCount(0);
                SearchPage.this.setCursor(Cursor.getDefaultCursor());
                btn.setBackground(defColor);
                return;
            }

            saveSearchName = searchName;

            // ?
            getSpectrumForQuery(searchName);

            // ?
            SearchPage.this.setCursor(Cursor.getDefaultCursor());

            // ??
            btn.setBackground(defColor);
        }
    }

    /**
     * All
     * SerarchPage?
     */
    class BtnAllListener implements ActionListener {

        /**
         * 
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            // ?
            JButton btn = btnAll;
            Color defColor = btn.getBackground();
            btn.setBackground(Color.PINK);
            btn.update(btn.getGraphics());

            // ?
            SearchPage.this.setCursor(waitCursor);

            // ??
            if (guiDbTableRowMap.isEmpty()) {
                // ?
                getSpectrumForQuery(StringUtils.EMPTY);
            }
            // ??
            else {
                // ?
                queryPlot.clear();
                compPlot.clear();
                resultPlot.clear();
                queryPlot.setPeaks(null, 0);
                compPlot.setPeaks(null, 1);
                resultPlot.setPeaks(null, 0);

                // PackageView?
                pkgView.initAllRecInfo();

                hitLabel.setText(" ");
                queryDbTable.clearSelection();

                fillGuiDbTableData(new ArrayList<GuiDbTableRow>(guiDbTableRowMap.values()));
            }
            // ?
            SearchPage.this.setCursor(Cursor.getDefaultCursor());

            // ??
            btn.setBackground(defColor);
        }
    }

    /**
     * ?Show Record
     * SerarchPage?
     */
    class PopupShowRecordListener implements ActionListener {

        private JTable eventTbl; // 

        /**
         * 
         * @param eventTbl ???
         */
        public PopupShowRecordListener(JTable eventTbl) {
            this.eventTbl = eventTbl;
        }

        /**
         * 
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            showRecordPage(eventTbl);
        }
    }

    /**
     * ?Multiple Display
     * SerarchPage?
     */
    class PopupMultipleDisplayListener implements ActionListener {

        private JTable eventTbl; // 

        /**
         * 
         * @param eventTbl ???
         */
        public PopupMultipleDisplayListener(JTable eventTbl) {
            this.eventTbl = eventTbl;
        }

        /**
         * 
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            // TODO
            // result record table -> select double rows -> right click -> multiple display
            CommonUtil.openBrowser(Constant.ExternalUrl.SHOW_MULTIPLE_RECORD_PAGE);

            //         // ?????
            //         int selRows[] = eventTbl.getSelectedRows();
            //
            //         // CGI??
            //         try {
            //            String reqUrl = baseUrl + "jsp/Display.jsp";
            //            String param = "";
            //
            //            int idCol = eventTbl.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_ID);
            //            int nameCol = eventTbl.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_NAME);
            //            int ionCol = eventTbl.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_ION);
            //            int siteCol = eventTbl.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_CONTRIBUTOR);
            //            for (int i = 0; i < selRows.length; i++) {
            //               int row = selRows[i];
            //               String name = (String)eventTbl.getValueAt(row, nameCol);
            //               String id = (String)eventTbl.getValueAt(row, idCol);
            //               String formula = "";
            //               String mass = "";
            //               String ion = (String)eventTbl.getValueAt(row, ionCol);
            //               name = URLEncoder.encode(name);
            //               String siteName = (String)eventTbl.getValueAt(row, siteCol);
            //               String site = "0";
            ////               for (int j = 0; j < siteNameList.length; j++) {
            ////                  if (siteName.equals(siteNameList[j])) {
            ////                     site = Integer.toString(j);
            ////                     break;
            ////                  }
            ////               }
            //               param += "id=" + name + "\t" + id + "\t" + formula + "\t" + mass + "\t"   + ion + "\t" + site + "&";
            //            }
            //            param = param.substring(0, param.length() - 1);
            //            LOGGER.info("url to take filename" + reqUrl + "<->" + param);
            //            URL url = new URL(reqUrl);
            //            URLConnection con = url.openConnection();
            //            con.setDoOutput(true);
            //            PrintStream out = new PrintStream(con.getOutputStream());
            //            out.print(param);
            //            out.close();
            //            String line;
            //            String filename = "";
            //            BufferedReader in = new BufferedReader(new InputStreamReader(
            //                  con.getInputStream()));
            //            while ((line = in.readLine()) != null) {
            //               filename += line;
            //            }
            //            in.close();
            //
            //            reqUrl += "?type=Multiple Display&" + "name=" + filename;
            //              LOGGER.info("open browser with" + reqUrl);
            //              Desktop.getDesktop().browse(new URI(reqUrl));
            //                  
            //         } catch (IOException | URISyntaxException ex) {
            //              LOGGER.error(ex.getMessage(),ex);
            //         }
        }
    }

    private void initSearchParameterSetting() {
        try {
            if (MassBankDirSyncThread.hasSyncDataToReInitialize) {
                // ?
                instInfo = new GetInstInfo();
                initInstInfo();

                // MS?
                initMsInfo();

                // ?
                initIonInfo();
                MassBankDirSyncThread.hasSyncDataToReInitialize = false;
            }
        } catch (SQLException e1) {
            LOGGER.error(e1.getMessage(), e1);
        }
    }
}