Example usage for javax.swing JTable rowAtPoint

List of usage examples for javax.swing JTable rowAtPoint

Introduction

In this page you can find the example usage for javax.swing JTable rowAtPoint.

Prototype

public int rowAtPoint(Point point) 

Source Link

Document

Returns the index of the row that point lies in, or -1 if the result is not in the range [0, getRowCount()-1].

Usage

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositMain.java

private void jobQueueMouseReleaseCommon(java.awt.event.MouseEvent evt, JTable table) {
    if (evt.isPopupTrigger()) {
        if (table.getSelectedRowCount() == 0) {
            int row = table.rowAtPoint(evt.getPoint());
            if (row > -1) {
                table.setRowSelectionInterval(row, row);
            }/*www  . java  2  s  .  c  o m*/
        }
        JPopupMenu menu = depositPresenter.getJobQueueMenu((JTable) evt.getSource());
        if (menu != null) {
            menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }
}

From source file:org.apache.jmeter.config.gui.ArgumentsPanel.java

/**
 * @param table {@link JTable}//from  www . j ava  2  s .c o  m
 * @return number of visible rows
 */
private static int getNumberOfVisibleRows(JTable table) {
    Rectangle vr = table.getVisibleRect();
    int first = table.rowAtPoint(vr.getLocation());
    vr.translate(0, vr.height);
    return table.rowAtPoint(vr.getLocation()) - first;
}

From source file:org.nuclos.client.main.MainController.java

private Map<String, Map<String, Action>> getCommandMap() {
    HashMap<String, Map<String, Action>> res = new HashMap<String, Map<String, Action>>();
    HashMap<String, Action> mainController = new HashMap<String, Action>();

    /* that's too cumbersome:
    mainController.put(/*from w  ww.  java  2s  . co m*/
       "cmdChangePassword",
       new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
       cmdChangePassword();
    }
       });
     */

    mainController.put("cmdDirectHelp", cmdDirectHelp);
    mainController.put("cmdShowPersonalTasks", cmdShowPersonalTasks);
    mainController.put("cmdShowTimelimitTasks", cmdShowTimelimitTasks);
    mainController.put("cmdShowPersonalSearchFilters", cmdShowPersonalSearchFilters);
    mainController.put("cmdChangePassword", cmdChangePassword);
    mainController.put("cmdOpenSettings", cmdOpenSettings);
    mainController.put("cmdOpenManagementConsole", cmdOpenManagementConsole);
    //mainController.put("cmdOpenEntityWizard", cmdOpenEntityWizard);
    mainController.put("cmdOpenRelationEditor", cmdOpenRelationEditor);
    mainController.put("cmdOpenCustomComponentWizard", cmdOpenCustomComponentWizard);
    //mainController.put("cmdRefreshClientCaches", cmdRefreshClientCaches);
    mainController.put("cmdSelectAll", cmdSelectAll);
    mainController.put("cmdHelpContents", cmdHelpContents);
    mainController.put("cmdShowAboutDialog", cmdShowAboutDialog);
    mainController.put("cmdShowProjectReleaseNotes", cmdShowProjectReleaseNotes);
    mainController.put("cmdShowNuclosReleaseNotes", cmdShowNuclosReleaseNotes);
    mainController.put("cmdLogoutExit", cmdLogoutExit);
    mainController.put("cmdWindowClosing", cmdWindowClosing);
    mainController.put("cmdExecuteRport", cmdExecuteRport);

    for (Method m : getClass().getDeclaredMethods()) {
        if (m.getName().startsWith("cmd")) {
            Class<?>[] pt = m.getParameterTypes();
            if (pt.length == 0 || (pt.length == 1 && pt[0].isAssignableFrom(ActionEvent.class))) {
                final Method fm = m;
                Action a = new AbstractAction(m.getName()) {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        miDelegator(e, fm);
                    }
                };
                mainController.put(m.getName(), a);
            }
        }
    }

    res.put("MainController", mainController);

    HashMap<String, Action> clipboardUtils = new HashMap<String, Action>();
    clipboardUtils.put("cutAction", new ClipboardUtils.CutAction());
    clipboardUtils.put("copyAction", new ClipboardUtils.CopyAction());
    clipboardUtils.put("pasteAction", new ClipboardUtils.PasteAction());

    res.put("ClipboardUtils", clipboardUtils);

    HashMap<String, Action> dev = new HashMap<String, Action>();
    dev.put("jmsNotification", new AbstractAction("Test JMS notification") {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = JOptionPane.showInputDialog(getMainFrame(), "Topic: Message");
            if (s == null)
                return;
            String[] a = s.split(": *");
            if (a.length == 2) {
                // testFacadeRemote.testClientNotification(a[0], a[1]);
                throw new UnsupportedOperationException("TestFacade removed");
            } else {
                JOptionPane.showMessageDialog(getMainFrame(), "Wrong input format");
            }
        }
    });

    dev.put("webPrefs", new AbstractAction("Test Web Prefs-Access") {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = JOptionPane.showInputDialog(getMainFrame(), "Access-Path");
            if (s == null)
                return;
            try {
                Map<String, String> m = getWebAccessPrefs().getPrefsMap(s);
                StringBuilder sb = new StringBuilder();
                for (String k : m.keySet())
                    sb.append(k).append(": ").append(m.get(k)).append("\n");
                JOptionPane.showMessageDialog(getMainFrame(), sb.toString());
            } catch (CommonBusinessException e1) {
                Errors.getInstance().showExceptionDialog(getMainFrame(), e1);
            }
        }
    });

    dev.put("uiDefaults", new AbstractAction("UIDefaults") {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFrame out = new JFrame("UIDefaults");
            out.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            out.getContentPane().setLayout(new BorderLayout());
            final UIDefTableModel mdl = new UIDefTableModel();
            final JTable contentTable = new JTable(mdl);
            JScrollPane sp = new JScrollPane(contentTable);
            out.getContentPane().add(sp, BorderLayout.CENTER);

            UIDefaults defs = UIManager.getDefaults();
            for (Object key : CollectionUtils.iterableEnum((defs.keys())))
                mdl.add(key.toString(), defs.get(key));
            mdl.sort();

            contentTable.getColumnModel().getColumn(1).setCellRenderer(new UIDefaultsRenderer());
            contentTable.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    int row = contentTable.rowAtPoint(e.getPoint());
                    mdl.forceValue(contentTable.convertRowIndexToModel(row));
                }
            });
            out.pack();
            out.setVisible(true);
        }
    });

    dev.put("checkJawin", new AbstractAction("Check Jawin") {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                SystemUtils.checkJawin();
                JOptionPane.showMessageDialog(Main.getInstance().getMainFrame(), "Jawin ok");
            } catch (Exception ex) {
                Errors.getInstance().showDetailedExceptionDialog(Main.getInstance().getMainFrame(), ex);
            }
        }
    });

    res.put("Dev", dev);

    return res;
}

From source file:org.nuclos.client.ui.collect.result.ResultController.java

/**
 * TODO: Make this package visible again.
 *//* w  w w.jav a2s .c om*/
public void setupResultPanel() {
    if (NuclosEntity.isNuclosEntity(getEntity().getName())) {
        this.getResultPanel().setActionsEnabled(false);
    }
    this.getResultPanel().addActionsVisibleListener(actionsVisibleListener);

    setupActions();

    // add selection listener for Result table:
    final JTable tblResult = this.getResultPanel().getResultTable();

    tblResult.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    tblResult.getSelectionModel().addListSelectionListener(newListSelectionListener(tblResult));

    this.getResultPanel().btnToggleSelectionMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getResultPanel().setToggleSelection(!getResultPanel().isToggleSelection());
        }
    });
    this.getResultPanel().btnSelectAllRows.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (tblResult.getRowCount() > 0) {
                tblResult.getSelectionModel().setSelectionInterval(0, tblResult.getRowCount() - 1);
            }
        }
    });
    this.getResultPanel().btnDeSelectAllRows.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tblResult.getSelectionModel().clearSelection();
        }
    });
    this.getResultPanel().addResultKeyListener(new ResultKeyListener() {
        @Override
        public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if (e.getKeyCode() == ESC) {
                if (!pressed) {
                    tblResult.getSelectionModel().clearSelection();
                    return true;
                }
            } else if (e.getKeyCode() == UP || e.getKeyCode() == DOWN) {
                if (pressed) {
                    /* Warum wird dies bentigt?
                     * BasicTableUI.actionPerformed(...) sendet ein ungewolltes changeSelection mit toggle=false bei PFEIL-NACH-OBEN/-UNTEN (siehe unten).
                     * Der Standard in der Ergebnisansicht soll aber ein umgedrehtes Verhalten fr Mausklicks sein. (siehe Implementierung 
                     *       ResultPanel: super.changeSelection(rowIndex, columnIndex, alternateSelectionToggle? !toggle: toggle, extend);)  
                     * 
                     * else if (!inSelection) {
                          *       moveWithinTableRange(table, dx, dy);
                          *       table.changeSelection(leadRow, leadColumn, false, extend);
                         * }
                     */
                    getResultPanel().setAlternateSelectionToggle(false);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            getResultPanel().setAlternateSelectionToggle(true);
                        }
                    });
                }
            }
            return false;
        }
    });

    // add mouse listener for double click in table:
    this.mouselistenerTableDblClick = new MouseAdapter() {

        private long lastClick = 0l;

        @Override
        public void mouseClicked(MouseEvent ev) {
            if (SwingUtilities.isLeftMouseButton(ev)) {
                if (lastClick + MainFrameTabbedPane.DOUBLE_CLICK_SPEED > System.currentTimeMillis()) {
                    int iRow = tblResult.rowAtPoint(ev.getPoint());
                    if (iRow >= 0 && iRow < tblResult.getRowCount()) {
                        tblResult.getSelectionModel().setSelectionInterval(iRow, iRow);
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                if (getSelectedCollectableFromTableModel() != null) {
                                    clctctl.cmdViewSelectedCollectables();
                                }
                            }
                        });
                    }
                }

                lastClick = System.currentTimeMillis();
            }
        }
    };
    getResultPanel().addDoubleClickMouseListener(this.mouselistenerTableDblClick);

    if (!SecurityCache.getInstance()
            .isActionAllowed(Actions.ACTION_WORKSPACE_CUSTOMIZE_ENTITY_AND_SUBFORM_COLUMNS)
            && getMainFrame().getWorkspace().isAssigned()) {
        getResultPanel().getResultTable().getTableHeader().setReorderingAllowed(false);
    }

    // change column ordering in table model when table columns are reordered by dragging a column with the mouse:
    getResultPanel().addColumnModelListener(newColumnModelListener());
    PreferencesUpdateListener pul = newResultTablePreferencesUpdateListener();
    getResultPanel().addColumnModelListener(pul);

    getResultPanel().addPopupMenuListener();
    getResultPanel().getSearchFilterBar().addEnabledListener(new ResetMainFilterEnabledListener());

    getResultPanel().setActionsVisible(
            getCollectController().getPreferences().getBoolean(RESULT_ACTIONS_VISIBLE, true));
}

From source file:org.nuclos.client.ui.collect.SubForm.java

/**
 * @Deprecated Never use this directly, instead use {@link #addToolbarMenuItems(List)}.
 *///from www  . j av  a2s .  com
private MouseListener newToolbarContextMenuListener(final JComponent parent, final JTable table) {
    MouseListener res = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent mev) {
            if (SwingUtilities.isRightMouseButton(mev)) {
                List<JComponent> items = new ArrayList<JComponent>();
                addToolbarMenuItems(items);
                if (items.isEmpty())
                    return;

                JPopupMenu popup = new JPopupMenu();
                for (JComponent c : items)
                    popup.add(c);
                popup.show(parent, mev.getX(), mev.getY());
            }
            if (SwingUtilities.isLeftMouseButton(mev) && mev.getClickCount() == 2) {
                int row = table.rowAtPoint(mev.getPoint());
                int column = table.columnAtPoint(mev.getPoint());
                LOG.info(StringUtils.concat("Doubleclick on subform: column=", column, ",row=", row));
                if (row == -1 || column == -1) {
                    if (toolbarMenuItems.get(ToolbarFunction.NEW.name()).isEnabled()) {
                        actionPerformed(ToolbarFunction.NEW.name());
                    }
                }
            }
        }

    };
    return res;
}

From source file:org.omegat.gui.align.AlignPanelController.java

/**
 * Display the align tool. The tool is not modal, so this call will return immediately.
 * //from  ww w .  j  av a  2s  . c o  m
 * @param parent
 *            Parent window of the align tool
 */
public void show(Component parent) {
    frame = new AlignMenuFrame();
    frame.setTitle(OStrings.getString("ALIGNER_PANEL"));
    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            closeFrame(frame);
        }
    });

    panel = new AlignPanel();

    ActionListener comparisonListener = e -> {
        ComparisonMode newValue = (ComparisonMode) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.comparisonMode && confirmReset(frame)) {
            aligner.comparisonMode = newValue;
            reloadBeads();
        } else {
            panel.comparisonComboBox.setSelectedItem(aligner.comparisonMode);
        }
    };
    panel.comparisonComboBox.addActionListener(comparisonListener);
    panel.comparisonComboBox.setRenderer(new EnumRenderer<ComparisonMode>("ALIGNER_ENUM_COMPARISON_MODE_"));

    ActionListener algorithmListener = e -> {
        AlgorithmClass newValue = (AlgorithmClass) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.algorithmClass && confirmReset(frame)) {
            aligner.algorithmClass = newValue;
            reloadBeads();
        } else {
            panel.algorithmComboBox.setSelectedItem(aligner.algorithmClass);
        }
    };
    panel.algorithmComboBox.addActionListener(algorithmListener);
    panel.algorithmComboBox.setRenderer(new EnumRenderer<AlgorithmClass>("ALIGNER_ENUM_ALGORITHM_CLASS_"));

    ActionListener calculatorListener = e -> {
        CalculatorType newValue = (CalculatorType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.calculatorType && confirmReset(frame)) {
            aligner.calculatorType = newValue;
            reloadBeads();
        } else {
            panel.calculatorComboBox.setSelectedItem(aligner.calculatorType);
        }
    };
    panel.calculatorComboBox.addActionListener(calculatorListener);
    panel.calculatorComboBox.setRenderer(new EnumRenderer<CalculatorType>("ALIGNER_ENUM_CALCULATOR_TYPE_"));

    ActionListener counterListener = e -> {
        CounterType newValue = (CounterType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.counterType && confirmReset(frame)) {
            aligner.counterType = newValue;
            reloadBeads();
        } else {
            panel.counterComboBox.setSelectedItem(aligner.counterType);
        }
    };
    panel.counterComboBox.addActionListener(counterListener);
    panel.counterComboBox.setRenderer(new EnumRenderer<CounterType>("ALIGNER_ENUM_COUNTER_TYPE_"));

    ActionListener segmentingListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.segment && confirmReset(frame)) {
                aligner.segment = newValue;
                reloadBeads();
            } else {
                panel.segmentingCheckBox.setSelected(aligner.segment);
                frame.segmentingItem.setSelected(aligner.segment);
            }
        }
    };
    panel.segmentingCheckBox.addActionListener(segmentingListener);
    frame.segmentingItem.addActionListener(segmentingListener);

    ActionListener segmentingRulesListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                SegmentationCustomizer customizer = new SegmentationCustomizer(false, SRX.getDefault(),
                        Core.getSegmenter().getSRX(), null);
                if (customizer.show(frame)) {
                    customizedSRX = customizer.getResult();
                    Core.setSegmenter(new Segmenter(customizedSRX));
                    reloadBeads();
                }
            }
        }
    };
    panel.segmentingRulesButton.addActionListener(segmentingRulesListener);
    frame.segmentingRulesItem.addActionListener(segmentingRulesListener);

    ActionListener filterSettingsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                FiltersCustomizer customizer = new FiltersCustomizer(false,
                        FilterMaster.createDefaultFiltersConfig(), Core.getFilterMaster().getConfig(), null);
                if (customizer.show(frame)) {
                    customizedFilters = customizer.getResult();
                    Core.setFilterMaster(new FilterMaster(customizedFilters));
                    aligner.clearLoaded();
                    reloadBeads();
                }
            }
        }
    };
    panel.fileFilterSettingsButton.addActionListener(filterSettingsListener);
    frame.fileFilterSettingsItem.addActionListener(filterSettingsListener);

    TableCellRenderer renderer = new MultilineCellRenderer();
    panel.table.setDefaultRenderer(Object.class, renderer);
    panel.table.setDefaultRenderer(Boolean.class, renderer);
    panel.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeRows(panel.table);
        }
    });

    ActionListener oneAdjustListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            boolean up = e.getSource().equals(panel.moveUpButton) || e.getSource().equals(frame.moveUpItem);
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
                int trgRow = up ? model.prevBeadFromRow(rows[0]) : model.nextBeadFromRow(rows[rows.length - 1]);
                moveRows(rows, col, trgRow);
            } else {
                int offset = up ? -1 : 1;
                slideRows(rows, col, offset);
            }
        }
    };
    panel.moveUpButton.addActionListener(oneAdjustListener);
    frame.moveUpItem.addActionListener(oneAdjustListener);
    panel.moveDownButton.addActionListener(oneAdjustListener);
    frame.moveDownItem.addActionListener(oneAdjustListener);

    ActionListener mergeListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if (rows.length == 1) {
                rows = new int[] { rows[0], model.nextNonEmptyCell(rows[0], col) };
            }
            int beads = model.beadsInRowSpan(rows);
            if (beads < 1) {
                // Do nothing
            } else if (beads == 1) {
                mergeRows(rows, col);
            } else {
                moveRows(rows, col, rows[0]);
            }
        }
    };
    panel.mergeButton.addActionListener(mergeListener);
    frame.mergeItem.addActionListener(mergeListener);

    ActionListener splitListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            int beads = model.beadsInRowSpan(rows);
            if (beads != 1) {
                // Do nothing
            } else if (rows.length == 1) {
                splitRow(rows[0], col);
            } else {
                splitBead(rows, col);
            }
        }
    };
    panel.splitButton.addActionListener(splitListener);
    frame.splitItem.addActionListener(splitListener);

    ActionListener editListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            int row = panel.table.getSelectedRow();
            int col = panel.table.getSelectedColumn();
            editRow(row, col);
        }
    };
    panel.editButton.addActionListener(editListener);
    frame.editItem.addActionListener(editListener);

    ListSelectionListener selectionListener = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateCommandAvailability(panel, frame);
        }
    };
    panel.table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener);
    panel.table.getSelectionModel().addListSelectionListener(selectionListener);

    ActionListener saveListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!confirmSaveTMX(panel)) {
                return;
            }
            while (true) {
                JFileChooser chooser = new JFileChooser();
                chooser.setSelectedFile(new File(defaultSaveDir, getOutFileName()));
                chooser.setDialogTitle(OStrings.getString("ALIGNER_PANEL_DIALOG_SAVE"));
                if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(frame)) {
                    File file = chooser.getSelectedFile();
                    if (file.isFile()) {
                        if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(frame,
                                StringUtil.format(OStrings.getString("ALIGNER_PANEL_DIALOG_OVERWRITE"),
                                        file.getName()),
                                OStrings.getString("ALIGNER_DIALOG_WARNING_TITLE"),
                                JOptionPane.WARNING_MESSAGE)) {
                            continue;
                        }
                    }
                    List<MutableBead> beads = ((BeadTableModel) panel.table.getModel()).getData();
                    try {
                        aligner.writePairsToTMX(file,
                                MutableBead.beadsToEntries(aligner.srcLang, aligner.trgLang, beads));
                        modified = false;
                    } catch (Exception ex) {
                        Log.log(ex);
                        JOptionPane.showMessageDialog(frame, OStrings.getString("ALIGNER_PANEL_SAVE_ERROR"),
                                OStrings.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
                    }
                }
                break;
            }
        }
    };
    panel.saveButton.addActionListener(saveListener);
    frame.saveItem.addActionListener(saveListener);

    ActionListener resetListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                if (phase == Phase.ALIGN) {
                    aligner.restoreDefaults();
                }
                reloadBeads();
            }
        }
    };
    panel.resetButton.addActionListener(resetListener);
    frame.resetItem.addActionListener(resetListener);

    ActionListener reloadListener = e -> {
        if (confirmReset(frame)) {
            aligner.clearLoaded();
            reloadBeads();
        }
    };
    frame.reloadItem.addActionListener(reloadListener);

    ActionListener removeTagsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.removeTags && confirmReset(frame)) {
                aligner.removeTags = newValue;
                aligner.clearLoaded();
                reloadBeads();
            } else {
                panel.removeTagsCheckBox.setSelected(aligner.removeTags);
                frame.removeTagsItem.setSelected(aligner.removeTags);
            }
        }
    };
    panel.removeTagsCheckBox.addActionListener(removeTagsListener);
    frame.removeTagsItem.addActionListener(removeTagsListener);

    panel.continueButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            phase = Phase.EDIT;
            updatePanel();
        }
    });

    ActionListener highlightListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doHighlight = ((AbstractButton) e.getSource()).isSelected();
            updateHighlight();
        }
    };
    panel.highlightCheckBox.addActionListener(highlightListener);
    frame.highlightItem.addActionListener(highlightListener);

    ActionListener highlightPatternListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            PatternPanelController patternEditor = new PatternPanelController(highlightPattern);
            highlightPattern = patternEditor.show(frame);
            Preferences.setPreference(Preferences.ALIGNER_HIGHLIGHT_PATTERN, highlightPattern.pattern());
            updateHighlight();
        }
    };
    panel.highlightPatternButton.addActionListener(highlightPatternListener);
    frame.highlightPatternItem.addActionListener(highlightPatternListener);

    frame.markAcceptedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.ACCEPTED, panel.table.getSelectedRows());
        }
    });

    frame.markNeedsReviewItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.NEEDS_REVIEW, panel.table.getSelectedRows());
        }
    });

    frame.clearMarkItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.DEFAULT, panel.table.getSelectedRows());
        }
    });

    frame.toggleSelectedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleEnabled(panel.table.getSelectedRows());
        }
    });

    frame.closeItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            closeFrame(frame);
        }
    });

    frame.keepAllItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(true);
        }
    });

    frame.keepNoneItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(false);
        }
    });

    frame.realignPendingItem.addActionListener(e -> {
        realignPending();
    });

    frame.pinpointAlignStartItem.addActionListener(e -> {
        phase = Phase.PINPOINT;
        ppRow = panel.table.getSelectedRow();
        ppCol = panel.table.getSelectedColumn();
        panel.table.clearSelection();
        updatePanel();
    });

    frame.pinpointAlignEndItem.addActionListener(e -> {
        pinpointAlign(panel.table.getSelectedRow(), panel.table.getSelectedColumn());
    });

    frame.pinpointAlignCancelItem.addActionListener(e -> {
        phase = Phase.EDIT;
        ppRow = -1;
        ppCol = -1;
        panel.table.repaint();
        updatePanel();
    });

    panel.table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (phase == Phase.PINPOINT) {
                JTable table = (JTable) e.getSource();
                int row = table.rowAtPoint(e.getPoint());
                int col = table.columnAtPoint(e.getPoint());
                pinpointAlign(row, col);
            }
        }
    });

    frame.resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | KeyEvent.SHIFT_DOWN_MASK));
    frame.realignPendingItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.saveItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.closeItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    // emacs-like keys for table navigation
    // See javax.swing.plaf.BasicTableUI.Actions for supported action names.
    setKeyboardShortcut(panel.table, "selectNextRow", 'n');
    setKeyboardShortcut(panel.table, "selectNextRowExtendSelection", 'N');
    setKeyboardShortcut(panel.table, "selectPreviousRow", 'p');
    setKeyboardShortcut(panel.table, "selectPreviousRowExtendSelection", 'P');
    setKeyboardShortcut(panel.table, "selectNextColumn", 'f');
    setKeyboardShortcut(panel.table, "selectNextColumnExtendSelection", 'F');
    setKeyboardShortcut(panel.table, "selectPreviousColumn", 'b');
    setKeyboardShortcut(panel.table, "selectPreviousColumnExtendSelection", 'B');

    panel.table.setTransferHandler(new AlignTransferHandler());
    panel.table.addPropertyChangeListener("dropLocation", new DropLocationListener());
    if (Preferences.isPreference(Preferences.PROJECT_FILES_USE_FONT)) {
        try {
            String fontName = Preferences.getPreference(Preferences.TF_SRC_FONT_NAME);
            int fontSize = Integer.parseInt(Preferences.getPreference(Preferences.TF_SRC_FONT_SIZE));
            panel.table.setFont(new Font(fontName, Font.PLAIN, fontSize));
        } catch (Exception e) {
            Log.log(e);
        }
    }

    // Set initial state
    updateHighlight();
    updatePanel();
    reloadBeads();

    frame.add(panel);
    frame.pack();
    frame.setMinimumSize(frame.getSize());
    frame.setLocationRelativeTo(parent);
    frame.setVisible(true);
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.GrandLivrePanel.java

/**
 * Cree un JTable contenant les ecritures du compte pass en argument
 * /*from   w w  w. jav a  2  s.co m*/
 * @param compte
 * @return null si aucune ecriture
 */
private JTable createJTableCompte(Compte compte) {

    // on cree la JTable
    final JTable tableTmp = creerJTable(compte);

    if (tableTmp != null) {

        // On met en place le renderer
        EcritureGrandLivreRenderer ecritureRenderer = new EcritureGrandLivreRenderer(
                ((TableSorter) tableTmp.getModel()));

        for (int j = 0; j < tableTmp.getColumnCount(); j++) {
            tableTmp.getColumnModel().getColumn(j).setCellRenderer(ecritureRenderer);
        }

        // Gestion de la souris sur la JTable
        tableTmp.addMouseListener(new MouseAdapter() {

            public void mousePressed(final MouseEvent mE) {

                if (mE.getButton() == MouseEvent.BUTTON3) {
                    JPopupMenu menuDroit = new JPopupMenu();

                    menuDroit.add(new AbstractAction("Voir la source") {

                        public void actionPerformed(ActionEvent e) {
                            int row = tableTmp.rowAtPoint(mE.getPoint());

                            TableSorter s = (TableSorter) tableTmp.getModel();

                            int modelIndex = s.modelIndex(row);
                            ConsultCompteModel consultCompteModel = ((ConsultCompteModel) s.getTableModel());
                            Ecriture ecriture = consultCompteModel.getEcritures().get(modelIndex);

                            MouvementSQLElement.showSource(ecriture.getIdMvt());

                        }
                    });
                    menuDroit.show(mE.getComponent(), mE.getX(), mE.getY());
                }
            }
        });

    }
    return tableTmp;
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.PlanComptableGPanel.java

public JTable creerJTable(ClasseCompte ccTmp) { // NO_UCD

    final PlanComptableGModel model;
    if (this.radioCompteDeveloppe.isSelected()) {
        model = new PlanComptableGModel(ccTmp, 3);
    } else if (this.radioCompteAbrege.isSelected()) {
        model = new PlanComptableGModel(ccTmp, 2);
    } else {//from  w  ww .  j  av a  2s .c  o m
        model = new PlanComptableGModel(ccTmp, 1);
    }

    final JTable table = new JTable(model) {
        public JToolTip createToolTip() {
            JMultiLineToolTip t = new JMultiLineToolTip();
            t.setFixedWidth(500);
            return t;
        }
    };

    table.getColumnModel().getColumn(0).setCellRenderer(new PlanComptableCellRenderer(0));
    table.getColumnModel().getColumn(1).setCellRenderer(new PlanComptableCellRenderer(0));

    // TODO calcul de la taille de la colone numero de compte
    table.getColumnModel().getColumn(0).setMaxWidth(90);

    table.getTableHeader().setReorderingAllowed(false);

    table.addMouseMotionListener(new MouseMotionAdapter() {
        int lastRow = -1;

        public void mouseMoved(final MouseEvent e) {

            final Point p = new Point(e.getX(), e.getY());

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    final int row = table.rowAtPoint(p);
                    if (lastRow != row) {
                        lastRow = row;
                        String strTmp = ((Compte) (model.getComptes().get(lastRow))).getInfos();

                        if (strTmp.length() != 0) {
                            table.setToolTipText(strTmp);
                        } else {
                            table.setToolTipText(null);
                        }

                    }
                }
            });

        }
    });

    if (this.actionClickDroit != null) {
        // System.out.println("Ajout menu droit");
        table.addMouseListener(new MouseAdapter() {

            public void mousePressed(MouseEvent e) {

                if (e.getButton() == MouseEvent.BUTTON3) {
                    actionDroitTable(e, table);
                }
            }
        });
    }

    // Enable row selection (default)
    /**
     * table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(true);
     * 
     * table.setSelectionMode(table.getSelectionModel().MULTIPLE_INTERVAL_SELECTION);
     */

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent e) {
            int selectedRow = table.getSelectedRow();
            if (selectedRow < 0) {
                // Pas de selection
                textInfos.setText("Pas de compte slctionn");
            } else {
                textInfos.setText(((Compte) (model.getComptes().get(selectedRow))).getInfos());
            }
        }
    });

    return table;
}

From source file:org.revager.tools.GUITools.java

/**
 * Creates a new standard table.//from   ww w  .j ava  2s. c o  m
 * 
 * @param model
 *            the table model
 * @param showHeader
 *            true if the header of the table should be visible
 * 
 * @return the newly created table
 */
@SuppressWarnings("serial")
public static JTable newStandardTable(TableModel model, boolean showHeader) {
    /*
     * Prep. for rollover
     */
    if (lastRolloverKey == Integer.MAX_VALUE) {
        lastRolloverKey = 0;
    } else {
        lastRolloverKey++;
    }

    final int keyIdx = lastRolloverKey;

    rollOverRowIndex.put(keyIdx, -1);

    final JTable table = new JTable(model) {

        @Override
        public boolean editCellAt(int row, int column, java.util.EventObject e) {
            boolean result = super.editCellAt(row, column, e);
            final Component editor = getEditorComponent();

            TableCellRenderer renderer = this.getColumnModel().getColumn(column).getCellRenderer();
            Font cellFont = null;
            if (renderer instanceof DefaultTableCellRenderer) {
                cellFont = ((DefaultTableCellRenderer) renderer).getFont();
            }
            if (editor != null && editor instanceof JTextComponent) {
                JTextComponent jTextComponent = (JTextComponent) editor;
                if (e == null) {
                    jTextComponent.selectAll();
                } else {
                    SwingUtilities.invokeLater(jTextComponent::selectAll);
                }
                jTextComponent.setBorder(UI.MARKED_BORDER_INLINE);
                if (cellFont != null) {
                    jTextComponent.setFont(cellFont);
                }
                editor.requestFocusInWindow();
            }
            return result;
        }

        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {
            TableCellRenderer renderer = super.getCellRenderer(row, column);
            if (renderer instanceof DefaultTableCellRenderer) {
                ((DefaultTableCellRenderer) renderer).setBorder(new EmptyBorder(3, 3, 3, 3));
            }
            return renderer;
        }

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component comp = super.prepareRenderer(renderer, row, col);
            // Rollover
            comp.setBackground(getBackground());
            comp = super.prepareRenderer(renderer, row, col);
            if (!isRowSelected(row) && row == rollOverRowIndex.get(keyIdx)) {
                comp.setForeground(getForeground());
                comp.setBackground(UI.BLUE_BACKGROUND_COLOR);
            }

            // Tooltips
            JComponent jcomp = (JComponent) comp;
            if (renderer instanceof DefaultTableCellRenderer) {
                String toolTip = ((DefaultTableCellRenderer) renderer).getToolTipText();
                if (!StringUtils.isEmpty(toolTip)) {
                    jcomp.setToolTipText(toolTip);
                }
            }
            return comp;
        }
    };

    // Table properties
    table.setRowHeight(UI.TABLE_ROW_HEIGHT);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid(false);
    table.setShowHorizontalLines(true);
    table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

    // Rollover
    MouseInputAdapter rolloverListener = new MouseInputAdapter() {
        @Override
        public void mouseExited(MouseEvent e) {
            rollOverRowIndex.put(keyIdx, -1);
            table.repaint();
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            int row = table.rowAtPoint(e.getPoint());
            if (row != rollOverRowIndex.get(keyIdx)) {
                rollOverRowIndex.put(keyIdx, row);
                table.repaint();
            }
        }
    };
    table.addMouseMotionListener(rolloverListener);
    table.addMouseListener(rolloverListener);

    // Header
    if (!showHeader) {
        table.setTableHeader(null);
    }
    return table;
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public TransferHandler dragRows(final JTable table, final List<String> specs) {
    TransferHandler th = null;/*from   w  ww .j a va2s  . c o  m*/
    try {
        final DataFlavor ndf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
        final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
        final String charset = df.getParameter("charset");
        final Transferable transferable = new Transferable() {
            @Override
            public Object getTransferData(DataFlavor arg0) throws UnsupportedFlavorException, IOException {
                if (arg0.equals(ndf)) {
                    int[] rr = currentRowSelection; //table.getSelectedRows();
                    List<String> selseq = new ArrayList<String>(rr.length);
                    for (int r : rr) {
                        int i = table.convertRowIndexToModel(r);
                        selseq.add(specs.get(i));
                    }
                    return selseq;
                } else {
                    String ret = "";//makeCopyString();
                    for (int r = 0; r < table.getRowCount(); r++) {
                        Object o = table.getValueAt(r, 0);
                        if (o != null) {
                            ret += o.toString();
                        } else {
                            ret += "";
                        }
                        for (int c = 1; c < table.getColumnCount(); c++) {
                            o = table.getValueAt(r, c);
                            if (o != null) {
                                ret += "\t" + o.toString();
                            } else {
                                ret += "\t";
                            }
                        }
                        ret += "\n";
                    }
                    //return arg0.getReaderForText( this );
                    return new ByteArrayInputStream(ret.getBytes(charset));
                }
                //return ret;
            }

            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { df, ndf };
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor arg0) {
                if (arg0.equals(df) || arg0.equals(ndf)) {
                    return true;
                }
                return false;
            }
        };

        th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            public int getSourceActions(JComponent c) {
                return TransferHandler.COPY_OR_MOVE;
            }

            public boolean canImport(TransferHandler.TransferSupport support) {
                return true;
            }

            protected Transferable createTransferable(JComponent c) {
                currentRowSelection = table.getSelectedRows();

                return transferable;
            }

            public boolean importData(TransferHandler.TransferSupport support) {
                try {
                    System.err.println(table.getSelectedRows().length);

                    DataFlavor[] dfs = support.getDataFlavors();
                    if (support.isDataFlavorSupported(ndf)) {
                        Object obj = support.getTransferable().getTransferData(ndf);
                        ArrayList<String> seqs = (ArrayList<String>) obj;

                        /*ArrayList<String> newlist = new ArrayList<String>( serifier.lgse.size() );
                        for( int r = 0; r < table.getRowCount(); r++ ) {
                           int i = table.convertRowIndexToModel(r);
                           newlist.add( specs.get(i) );
                        }
                        serifier.lgseq.clear();
                        serifier.lgseq = newlist;*/

                        Point p = support.getDropLocation().getDropPoint();
                        int k = table.rowAtPoint(p);

                        specs.removeAll(seqs);
                        for (String s : seqs) {
                            specs.add(k++, s);
                        }

                        TableRowSorter<TableModel> trs = (TableRowSorter<TableModel>) table.getRowSorter();
                        trs.setSortKeys(null);

                        table.tableChanged(new TableModelEvent(table.getModel()));

                        return true;
                    } /* else if( support.isDataFlavorSupported( df ) ) {                     
                        Object obj = support.getTransferable().getTransferData( df );
                        InputStream is = (InputStream)obj;
                                
                        System.err.println( charset );
                        importReader( new BufferedReader(new InputStreamReader(is, charset)) );
                                
                        updateView();
                                
                        return true;
                      }  else if( support.isDataFlavorSupported( DataFlavor.stringFlavor ) ) {                     
                        Object obj = support.getTransferable().getTransferData( DataFlavor.stringFlavor );
                        String str = (String)obj;
                        importReader( new BufferedReader( new StringReader(str) ) );
                                
                        updateView();
                                
                        return true;
                      }*/
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
    return th;
}