Search in sources :

Example 1 with LuceneDataStoreImpl

use of gate.persist.LuceneDataStoreImpl in project gate-core by GateNLP.

the class LuceneDataStoreSearchGUI method setTarget.

/**
 * Called by the GUI when this viewer/editor has to initialise itself
 * for a specific object.
 *
 * @param target the object (be it a {@link gate.Resource},
 *          {@link gate.DataStore}or whatever) this viewer has to
 *          display
 */
@Override
public void setTarget(Object target) {
    if (!(target instanceof LuceneDataStoreImpl) && !(target instanceof Searcher)) {
        throw new IllegalArgumentException("The GATE LuceneDataStoreSearchGUI can only be used with a GATE LuceneDataStores!\n" + target.getClass().toString() + " is not a GATE LuceneDataStore or an object of Searcher!");
    }
    this.target = target;
    // standalone Java application
    if (target instanceof LuceneDataStoreImpl) {
        ((LuceneDataStoreImpl) target).addDatastoreListener(this);
        corpusToSearchIn.setEnabled(true);
        searcher = ((LuceneDataStoreImpl) target).getSearcher();
        updateSetsTypesAndFeatures();
        try {
            // get the corpus names from the datastore
            java.util.List<String> corpusPIds = ((LuceneDataStoreImpl) target).getLrIds(SerialCorpusImpl.class.getName());
            if (corpusIds != null) {
                for (Object corpusPId : corpusPIds) {
                    String name = ((LuceneDataStoreImpl) target).getLrName(corpusPId);
                    this.corpusIds.add(corpusPId);
                    // add the corpus name to combobox
                    ((DefaultComboBoxModel<String>) corpusToSearchIn.getModel()).addElement(name);
                }
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    corpusToSearchIn.updateUI();
                    corpusToSearchIn.setSelectedItem(Constants.ENTIRE_DATASTORE);
                }
            });
        } catch (PersistenceException e) {
            System.out.println("Couldn't find any available corpusIds.");
            throw new GateRuntimeException(e);
        }
    } else // Java Web Start application
    {
        searcher = (Searcher) target;
        corpusToSearchIn.setEnabled(false);
        // find out all annotation sets that are indexed
        try {
            annotationSetIDsFromDataStore = searcher.getIndexedAnnotationSetNames();
            allAnnotTypesAndFeaturesFromDatastore = searcher.getAnnotationTypesMap();
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    updateAnnotationSetsList();
                }
            });
        } catch (SearchException e) {
            throw new GateRuntimeException(e);
        }
    }
}
Also used : Searcher(gate.creole.annic.Searcher) SearchException(gate.creole.annic.SearchException) LuceneDataStoreImpl(gate.persist.LuceneDataStoreImpl) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel) SerialCorpusImpl(gate.corpora.SerialCorpusImpl) GateRuntimeException(gate.util.GateRuntimeException) PersistenceException(gate.persist.PersistenceException) EventObject(java.util.EventObject)

Example 2 with LuceneDataStoreImpl

use of gate.persist.LuceneDataStoreImpl in project gate-core by GateNLP.

the class LuceneDataStoreSearchGUI method initGui.

/**
 * Initialize the GUI.
 */
protected void initGui() {
    // see the global layout schema at the end
    setLayout(new BorderLayout());
    stringCollator = java.text.Collator.getInstance();
    stringCollator.setStrength(java.text.Collator.TERTIARY);
    Comparator<String> lastWordComparator = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            if (o1 == null || o2 == null) {
                return 0;
            }
            return stringCollator.compare(o1.substring(o1.trim().lastIndexOf(' ') + 1), o2.substring(o2.trim().lastIndexOf(' ') + 1));
        }
    };
    integerComparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 == null || o2 == null) {
                return 0;
            }
            return o1.compareTo(o2);
        }
    };
    /**
     ********************************
     * Stack view configuration frame *
     *********************************
     */
    configureStackViewFrame = new ConfigureStackViewFrame("Stack view configuration");
    configureStackViewFrame.setIconImage(((ImageIcon) MainFrame.getIcon("WindowNew")).getImage());
    configureStackViewFrame.setLocationRelativeTo(LuceneDataStoreSearchGUI.this);
    configureStackViewFrame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ESCAPE"), "close row manager");
    configureStackViewFrame.getRootPane().getActionMap().put("close row manager", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            configureStackViewFrame.setVisible(false);
        }
    });
    configureStackViewFrame.validate();
    configureStackViewFrame.setSize(200, 300);
    configureStackViewFrame.pack();
    // called when Gate is exited, in case the user doesn't close the
    // datastore
    MainFrame.getInstance().addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            // no parent so need to be disposed explicitly
            configureStackViewFrame.dispose();
        }
    });
    /**
     ***********
     * Top panel *
     ************
     */
    JPanel topPanel = new JPanel(new GridBagLayout());
    topPanel.setOpaque(false);
    topPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 0, 3));
    GridBagConstraints gbc = new GridBagConstraints();
    // first column, three rows span
    queryTextArea = new QueryTextArea();
    queryTextArea.setToolTipText("<html>Enter a query to search the datastore." + "<br><small>'{' or '.' activate auto-completion." + "<br>Ctrl+Enter add a new line.</small></html>");
    queryTextArea.setLineWrap(true);
    gbc.gridheight = 3;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.insets = new Insets(0, 0, 0, 4);
    topPanel.add(new JScrollPane(queryTextArea), gbc);
    gbc.gridheight = 1;
    gbc.weightx = 0;
    gbc.weighty = 0;
    gbc.insets = new Insets(0, 0, 0, 0);
    // second column, first row
    gbc.gridx = GridBagConstraints.RELATIVE;
    topPanel.add(new JLabel("Corpus: "), gbc);
    corpusToSearchIn = new JComboBox<String>();
    corpusToSearchIn.addItem(Constants.ENTIRE_DATASTORE);
    corpusToSearchIn.setPrototypeDisplayValue(Constants.ENTIRE_DATASTORE);
    corpusToSearchIn.setToolTipText("Select the corpus to search in.");
    if (target == null || target instanceof Searcher) {
        corpusToSearchIn.setEnabled(false);
    }
    corpusToSearchIn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ie) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    updateAnnotationSetsList();
                }
            });
        }
    });
    topPanel.add(corpusToSearchIn, gbc);
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    topPanel.add(new JLabel("Annotation set: "), gbc);
    annotationSetsToSearchIn = new JComboBox<String>();
    annotationSetsToSearchIn.setPrototypeDisplayValue(Constants.COMBINED_SET);
    annotationSetsToSearchIn.setToolTipText("Select the annotation set to search in.");
    annotationSetsToSearchIn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ie) {
            updateAnnotationTypesList();
        }
    });
    topPanel.add(annotationSetsToSearchIn, gbc);
    // refresh button
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    RefreshAnnotationSetsAndFeaturesAction refreshAction = new RefreshAnnotationSetsAndFeaturesAction();
    JButton refreshTF = new ButtonBorder(new Color(240, 240, 240), new Insets(4, 2, 4, 3), false);
    refreshTF.setAction(refreshAction);
    topPanel.add(refreshTF, gbc);
    // second column, second row
    gbc.gridy = 1;
    JLabel noOfResultsLabel = new JLabel("Results: ");
    topPanel.add(noOfResultsLabel, gbc);
    numberOfResultsSlider = new JSlider(1, 1100, 50);
    numberOfResultsSlider.setToolTipText("50 results per page");
    numberOfResultsSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            if (numberOfResultsSlider.getValue() > (numberOfResultsSlider.getMaximum() - 100)) {
                numberOfResultsSlider.setToolTipText("Retrieve all results.");
                nextResults.setText("Retrieve all results.");
                nextResultsAction.setEnabled(false);
            } else {
                numberOfResultsSlider.setToolTipText("Retrieve " + numberOfResultsSlider.getValue() + " results per page.");
                nextResults.setText("Next page of " + numberOfResultsSlider.getValue() + " results");
                if (searcher.getHits().length == noOfResults) {
                    nextResultsAction.setEnabled(true);
                }
            }
            // show the tooltip each time the value change
            ToolTipManager.sharedInstance().mouseMoved(new MouseEvent(numberOfResultsSlider, MouseEvent.MOUSE_MOVED, 0, 0, 0, 0, 0, false));
        }
    });
    // always show the tooltip for this component
    numberOfResultsSlider.addMouseListener(new MouseAdapter() {

        ToolTipManager toolTipManager = ToolTipManager.sharedInstance();

        int initialDelay, reshowDelay, dismissDelay;

        boolean enabled;

        @Override
        public void mouseEntered(MouseEvent e) {
            initialDelay = toolTipManager.getInitialDelay();
            reshowDelay = toolTipManager.getReshowDelay();
            dismissDelay = toolTipManager.getDismissDelay();
            enabled = toolTipManager.isEnabled();
            toolTipManager.setInitialDelay(0);
            toolTipManager.setReshowDelay(0);
            toolTipManager.setDismissDelay(Integer.MAX_VALUE);
            toolTipManager.setEnabled(true);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            toolTipManager.setInitialDelay(initialDelay);
            toolTipManager.setReshowDelay(reshowDelay);
            toolTipManager.setDismissDelay(dismissDelay);
            toolTipManager.setEnabled(enabled);
        }
    });
    gbc.insets = new Insets(5, 0, 0, 0);
    topPanel.add(numberOfResultsSlider, gbc);
    gbc.insets = new Insets(0, 0, 0, 0);
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    JLabel contextWindowLabel = new JLabel("Context size: ");
    topPanel.add(contextWindowLabel, gbc);
    contextSizeSlider = new JSlider(1, 50, 5);
    contextSizeSlider.setToolTipText("Display 5 tokens of context in the results.");
    contextSizeSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            contextSizeSlider.setToolTipText("Display " + contextSizeSlider.getValue() + " tokens of context in the results.");
            ToolTipManager.sharedInstance().mouseMoved(new MouseEvent(contextSizeSlider, MouseEvent.MOUSE_MOVED, 0, 0, 0, 0, 0, false));
        }
    });
    // always show the tooltip for this component
    contextSizeSlider.addMouseListener(new MouseAdapter() {

        ToolTipManager toolTipManager = ToolTipManager.sharedInstance();

        int initialDelay, reshowDelay, dismissDelay;

        boolean enabled;

        @Override
        public void mouseEntered(MouseEvent e) {
            initialDelay = toolTipManager.getInitialDelay();
            reshowDelay = toolTipManager.getReshowDelay();
            dismissDelay = toolTipManager.getDismissDelay();
            enabled = toolTipManager.isEnabled();
            toolTipManager.setInitialDelay(0);
            toolTipManager.setReshowDelay(0);
            toolTipManager.setDismissDelay(Integer.MAX_VALUE);
            toolTipManager.setEnabled(true);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            toolTipManager.setInitialDelay(initialDelay);
            toolTipManager.setReshowDelay(reshowDelay);
            toolTipManager.setDismissDelay(dismissDelay);
            toolTipManager.setEnabled(enabled);
        }
    });
    gbc.insets = new Insets(5, 0, 0, 0);
    topPanel.add(contextSizeSlider, gbc);
    gbc.insets = new Insets(0, 0, 0, 0);
    // second column, third row
    gbc.gridy = 2;
    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    executeQueryAction = new ExecuteQueryAction();
    JButton executeQuery = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 2, 0, 3), false);
    executeQuery.setAction(executeQueryAction);
    panel.add(executeQuery);
    ClearQueryAction clearQueryAction = new ClearQueryAction();
    JButton clearQueryTF = new ButtonBorder(new Color(240, 240, 240), new Insets(4, 2, 4, 3), false);
    clearQueryTF.setAction(clearQueryAction);
    panel.add(Box.createHorizontalStrut(5));
    panel.add(clearQueryTF);
    nextResultsAction = new NextResultsAction();
    nextResultsAction.setEnabled(false);
    nextResults = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 0, 0, 3), false);
    nextResults.setAction(nextResultsAction);
    panel.add(Box.createHorizontalStrut(5));
    panel.add(nextResults);
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    topPanel.add(panel, gbc);
    // will be added to the GUI via a split panel
    /**
     **************
     * Center panel *
     ***************
     */
    // these components will be used in updateStackView()
    centerPanel = new AnnotationStack(150, 30);
    configureStackViewButton = new ButtonBorder(new Color(250, 250, 250), new Insets(0, 0, 0, 3), true);
    configureStackViewButton.setHorizontalAlignment(SwingConstants.LEFT);
    configureStackViewButton.setAction(new ConfigureStackViewAction());
    // will be added to the GUI via a split panel
    /**
     *******************
     * Bottom left panel *
     ********************
     */
    JPanel bottomLeftPanel = new JPanel(new GridBagLayout());
    bottomLeftPanel.setOpaque(false);
    gbc = new GridBagConstraints();
    // title of the table, results options, export and next results
    // button
    gbc.gridy = 0;
    panel = new JPanel();
    panel.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    titleResults = new JLabel("Results");
    titleResults.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    panel.add(titleResults);
    panel.add(Box.createHorizontalStrut(5), gbc);
    exportResultsAction = new ExportResultsAction();
    exportResultsAction.setEnabled(false);
    JButton exportToHTML = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 0, 0, 3), false);
    exportToHTML.setAction(exportResultsAction);
    panel.add(exportToHTML, gbc);
    bottomLeftPanel.add(panel, gbc);
    // table of results
    resultTableModel = new ResultTableModel();
    resultTable = new XJTable(resultTableModel);
    resultTable.setDefaultRenderer(String.class, new ResultTableCellRenderer());
    resultTable.setEnableHidingColumns(true);
    resultTable.addMouseListener(new MouseAdapter() {

        private JPopupMenu mousePopup;

        JMenuItem menuItem;

        @Override
        public void mousePressed(MouseEvent e) {
            int row = resultTable.rowAtPoint(e.getPoint());
            if (e.isPopupTrigger() && !resultTable.isRowSelected(row)) {
                // if right click outside the selection then reset selection
                resultTable.getSelectionModel().setSelectionInterval(row, row);
            }
            if (e.isPopupTrigger()) {
                createPopup();
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                createPopup();
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        private void createPopup() {
            mousePopup = new JPopupMenu();
            menuItem = new JMenuItem("Remove the selected result" + (resultTable.getSelectedRowCount() > 1 ? "s" : ""));
            mousePopup.add(menuItem);
            menuItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    int[] rows = resultTable.getSelectedRows();
                    for (int i = 0; i < rows.length; i++) {
                        rows[i] = resultTable.rowViewToModel(rows[i]);
                    }
                    Arrays.sort(rows);
                    for (int i = rows.length - 1; i >= 0; i--) {
                        results.remove(rows[i]);
                    }
                    resultTable.clearSelection();
                    resultTableModel.fireTableDataChanged();
                    mousePopup.setVisible(false);
                }
            });
            if (target instanceof LuceneDataStoreImpl && SwingUtilities.getRoot(LuceneDataStoreSearchGUI.this) instanceof MainFrame) {
                menuItem = new JMenuItem("Open the selected document" + (resultTable.getSelectedRowCount() > 1 ? "s" : ""));
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        Set<Pattern> patterns = new HashSet<Pattern>();
                        Set<String> documentIds = new HashSet<String>();
                        for (int rowView : resultTable.getSelectedRows()) {
                            // create and display the document for this result
                            int rowModel = resultTable.rowViewToModel(rowView);
                            Pattern pattern = (Pattern) results.get(rowModel);
                            if (!documentIds.contains(pattern.getDocumentID())) {
                                patterns.add(pattern);
                                documentIds.add(pattern.getDocumentID());
                            }
                        }
                        if (patterns.size() > 10) {
                            Object[] possibleValues = { "Open the " + patterns.size() + " documents", "Don't open" };
                            int selectedValue = JOptionPane.showOptionDialog(LuceneDataStoreSearchGUI.this, "Do you want to open " + patterns.size() + " documents in the central tabbed pane ?", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[1]);
                            if (selectedValue == 1 || selectedValue == JOptionPane.CLOSED_OPTION) {
                                return;
                            }
                        }
                        for (final Pattern pattern : patterns) {
                            // create and display the document for this result
                            FeatureMap features = Factory.newFeatureMap();
                            features.put(DataStore.DATASTORE_FEATURE_NAME, target);
                            features.put(DataStore.LR_ID_FEATURE_NAME, pattern.getDocumentID());
                            final Document doc;
                            try {
                                doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", features);
                            } catch (gate.util.GateException e) {
                                e.printStackTrace();
                                return;
                            }
                            // show the expression in the document
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    MainFrame.getInstance().select(doc);
                                }
                            });
                            if (patterns.size() == 1) {
                                // wait some time for the document to be displayed
                                Date timeToRun = new Date(System.currentTimeMillis() + 2000);
                                Timer timer = new Timer("Annic show document timer", true);
                                timer.schedule(new TimerTask() {

                                    @Override
                                    public void run() {
                                        showResultInDocument(doc, pattern);
                                    }
                                }, timeToRun);
                            }
                        }
                    }
                });
                mousePopup.add(menuItem);
            }
        }
    });
    // resultTable.addMouseListener
    // when selection change in the result table
    // update the stack view and export button
    resultTable.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {

        @Override
        public void valueChanged(javax.swing.event.ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateStackView();
            }
        }
    });
    resultTable.setColumnSelectionAllowed(false);
    resultTable.setRowSelectionAllowed(true);
    resultTable.setSortable(true);
    resultTable.setComparator(ResultTableModel.LEFT_CONTEXT_COLUMN, lastWordComparator);
    resultTable.setComparator(ResultTableModel.RESULT_COLUMN, stringCollator);
    resultTable.setComparator(ResultTableModel.RIGHT_CONTEXT_COLUMN, stringCollator);
    JScrollPane tableScrollPane = new JScrollPane(resultTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.NORTH;
    gbc.gridy = 1;
    gbc.gridx = 0;
    gbc.insets = new Insets(0, 0, 0, 0);
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    gbc.weightx = 1;
    gbc.weighty = 1;
    bottomLeftPanel.add(tableScrollPane, gbc);
    /**
     ************************
     * Statistics tabbed pane *
     *************************
     */
    statisticsTabbedPane = new JTabbedPane();
    globalStatisticsTable = new XJTable() {

        @Override
        public boolean isCellEditable(int rowIndex, int vColIndex) {
            return false;
        }
    };
    globalStatisticsTableModel = new DefaultTableModel(new Object[] { "Annotation Type", "Count" }, 0);
    globalStatisticsTable.setModel(globalStatisticsTableModel);
    globalStatisticsTable.setComparator(0, stringCollator);
    globalStatisticsTable.setComparator(1, integerComparator);
    globalStatisticsTable.setSortedColumn(1);
    globalStatisticsTable.setAscending(false);
    globalStatisticsTable.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                updateQuery();
            }
        }

        private void updateQuery() {
            int caretPosition = queryTextArea.getCaretPosition();
            String query = queryTextArea.getText();
            String type = (String) globalStatisticsTable.getValueAt(globalStatisticsTable.getSelectedRow(), globalStatisticsTable.convertColumnIndexToView(0));
            String queryMiddle = "{" + type + "}";
            String queryLeft = (queryTextArea.getSelectionStart() == queryTextArea.getSelectionEnd()) ? query.substring(0, caretPosition) : query.substring(0, queryTextArea.getSelectionStart());
            String queryRight = (queryTextArea.getSelectionStart() == queryTextArea.getSelectionEnd()) ? query.substring(caretPosition, query.length()) : query.substring(queryTextArea.getSelectionEnd(), query.length());
            queryTextArea.setText(queryLeft + queryMiddle + queryRight);
        }
    });
    statisticsTabbedPane.addTab("Global", null, new JScrollPane(globalStatisticsTable), "Global statistics on the Corpus and Annotation Set selected.");
    statisticsTabbedPane.addMouseListener(new MouseAdapter() {

        private JPopupMenu mousePopup;

        JMenuItem menuItem;

        @Override
        public void mousePressed(MouseEvent e) {
            int tabIndex = statisticsTabbedPane.indexAtLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && tabIndex > 0) {
                createPopup(tabIndex);
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            int tabIndex = statisticsTabbedPane.indexAtLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && tabIndex > 0) {
                createPopup(tabIndex);
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        private void createPopup(final int tabIndex) {
            mousePopup = new JPopupMenu();
            if (tabIndex == 1) {
                menuItem = new JMenuItem("Clear table");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ie) {
                        oneRowStatisticsTableModel.setRowCount(0);
                    }
                });
            } else {
                menuItem = new JMenuItem("Close tab");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ie) {
                        statisticsTabbedPane.remove(tabIndex);
                    }
                });
            }
            mousePopup.add(menuItem);
        }
    });
    class RemoveCellEditorRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener {

        private JButton button;

        public RemoveCellEditorRenderer() {
            button = new JButton();
            button.setHorizontalAlignment(SwingConstants.CENTER);
            button.setIcon(MainFrame.getIcon("Delete"));
            button.setToolTipText("Remove this row.");
            button.setContentAreaFilled(false);
            button.setBorderPainted(false);
            button.setMargin(new Insets(0, 0, 0, 0));
            button.addActionListener(this);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int col) {
            button.setSelected(isSelected);
            return button;
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int editingRow = oneRowStatisticsTable.getEditingRow();
            fireEditingStopped();
            oneRowStatisticsTableModel.removeRow(oneRowStatisticsTable.rowViewToModel(editingRow));
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
            button.setSelected(isSelected);
            return button;
        }
    }
    oneRowStatisticsTable = new XJTable() {

        @Override
        public boolean isCellEditable(int rowIndex, int vColIndex) {
            return vColIndex == 2;
        }

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component c = super.prepareRenderer(renderer, row, col);
            if (c instanceof JComponent && col != 2) {
                // display a custom tooltip saved when adding statistics
                ((JComponent) c).setToolTipText("<html>" + oneRowStatisticsTableToolTips.get(rowViewToModel(row)) + "</html>");
            }
            return c;
        }
    };
    oneRowStatisticsTableModel = new DefaultTableModel(new Object[] { "Annotation Type/Feature", "Count", "" }, 0);
    oneRowStatisticsTable.setModel(oneRowStatisticsTableModel);
    oneRowStatisticsTable.getColumnModel().getColumn(2).setCellEditor(new RemoveCellEditorRenderer());
    oneRowStatisticsTable.getColumnModel().getColumn(2).setCellRenderer(new RemoveCellEditorRenderer());
    oneRowStatisticsTable.setComparator(0, stringCollator);
    oneRowStatisticsTable.setComparator(1, integerComparator);
    statisticsTabbedPane.addTab("One item", null, new JScrollPane(oneRowStatisticsTable), "<html>One item statistics.<br>" + "Right-click on an annotation<br>" + "to add statistics here.");
    oneRowStatisticsTableToolTips = new Vector<String>();
    // will be added to the GUI via a split panel
    /**
     ************************************************************
     * Vertical splits between top, center panel and bottom panel *
     *************************************************************
     */
    /**
     * ________________________________________
     * |               topPanel                 |
     * |__________________3_____________________|
     * |                                        |
     * |             centerPanel                |
     * |________2________ __________2___________|
     * |                 |                      |
     * | bottomLeftPanel 1 statisticsTabbedPane |
     * |_________________|______________________|
     *
     * 1 bottomSplitPane 2 centerBottomSplitPane 3 topBottomSplitPane
     */
    bottomSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    Dimension minimumSize = new Dimension(0, 0);
    bottomLeftPanel.setMinimumSize(minimumSize);
    statisticsTabbedPane.setMinimumSize(minimumSize);
    bottomSplitPane.add(bottomLeftPanel);
    bottomSplitPane.add(statisticsTabbedPane);
    bottomSplitPane.setOneTouchExpandable(true);
    bottomSplitPane.setResizeWeight(0.75);
    bottomSplitPane.setContinuousLayout(true);
    JSplitPane centerBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    centerBottomSplitPane.add(new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
    centerBottomSplitPane.add(bottomSplitPane);
    centerBottomSplitPane.setResizeWeight(0.5);
    centerBottomSplitPane.setContinuousLayout(true);
    JSplitPane topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    topBottomSplitPane.add(topPanel);
    topBottomSplitPane.add(centerBottomSplitPane);
    topBottomSplitPane.setContinuousLayout(true);
    add(topBottomSplitPane, BorderLayout.CENTER);
}
Also used : AnnotationStack(gate.gui.docview.AnnotationStack) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) ActionEvent(java.awt.event.ActionEvent) Document(gate.Document) Comparator(java.util.Comparator) BorderLayout(java.awt.BorderLayout) JSlider(javax.swing.JSlider) TableCellEditor(javax.swing.table.TableCellEditor) EmptyBorder(javax.swing.border.EmptyBorder) AbstractAction(javax.swing.AbstractAction) HashSet(java.util.HashSet) TableCellRenderer(javax.swing.table.TableCellRenderer) DefaultTableCellRenderer(javax.swing.table.DefaultTableCellRenderer) ToolTipManager(javax.swing.ToolTipManager) Searcher(gate.creole.annic.Searcher) Color(java.awt.Color) EventObject(java.util.EventObject) ActionListener(java.awt.event.ActionListener) JTable(javax.swing.JTable) XJTable(gate.swing.XJTable) EventObject(java.util.EventObject) JSplitPane(javax.swing.JSplitPane) MouseInputAdapter(javax.swing.event.MouseInputAdapter) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) XJTable(gate.swing.XJTable) JTabbedPane(javax.swing.JTabbedPane) DefaultTableModel(javax.swing.table.DefaultTableModel) JButton(javax.swing.JButton) WindowAdapter(java.awt.event.WindowAdapter) TimerTask(java.util.TimerTask) ChangeListener(javax.swing.event.ChangeListener) AbstractCellEditor(javax.swing.AbstractCellEditor) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) JComponent(javax.swing.JComponent) JScrollPane(javax.swing.JScrollPane) Pattern(gate.creole.annic.Pattern) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) LuceneDataStoreImpl(gate.persist.LuceneDataStoreImpl) Dimension(java.awt.Dimension) JPopupMenu(javax.swing.JPopupMenu) Date(java.util.Date) FeatureMap(gate.FeatureMap) ChangeEvent(javax.swing.event.ChangeEvent) Timer(java.util.Timer) WindowEvent(java.awt.event.WindowEvent)

Aggregations

Searcher (gate.creole.annic.Searcher)2 LuceneDataStoreImpl (gate.persist.LuceneDataStoreImpl)2 EventObject (java.util.EventObject)2 Document (gate.Document)1 FeatureMap (gate.FeatureMap)1 SerialCorpusImpl (gate.corpora.SerialCorpusImpl)1 Pattern (gate.creole.annic.Pattern)1 SearchException (gate.creole.annic.SearchException)1 AnnotationStack (gate.gui.docview.AnnotationStack)1 PersistenceException (gate.persist.PersistenceException)1 XJTable (gate.swing.XJTable)1 GateRuntimeException (gate.util.GateRuntimeException)1 BorderLayout (java.awt.BorderLayout)1 Color (java.awt.Color)1 Component (java.awt.Component)1 Dimension (java.awt.Dimension)1 GridBagConstraints (java.awt.GridBagConstraints)1 GridBagLayout (java.awt.GridBagLayout)1 Insets (java.awt.Insets)1 ActionEvent (java.awt.event.ActionEvent)1