Example usage for javax.swing.table JTableHeader addMouseListener

List of usage examples for javax.swing.table JTableHeader addMouseListener

Introduction

In this page you can find the example usage for javax.swing.table JTableHeader addMouseListener.

Prototype

public synchronized void addMouseListener(MouseListener l) 

Source Link

Document

Adds the specified mouse listener to receive mouse events from this component.

Usage

From source file:com.diversityarrays.kdxplore.trials.TrialViewPanel.java

public TrialViewPanel(WindowOpener<JFrame> windowOpener, OfflineData od,
        Transformer<Trial, Boolean> checkIfEditorActive, Consumer<Trial> onTraitInstancesRemoved,
        MessagePrinter mp) {//from   w  w  w  .  j  av a  2  s . c  o m
    super(new BorderLayout());

    this.windowOpener = windowOpener;
    this.checkIfEditorActive = checkIfEditorActive;
    this.onTraitInstancesRemoved = onTraitInstancesRemoved;
    this.messagePrinter = mp;

    this.offlineData = od;
    this.offlineData.addOfflineDataChangeListener(offlineDataChangeListener);
    KdxploreDatabase db = offlineData.getKdxploreDatabase();
    if (db != null) {
        db.addEntityChangeListener(trialChangeListener);
    }

    trialDataTable.setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialDataTable, true));
    trialPropertiesTable
            .setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialPropertiesTable, true));

    // Note: Can't use renderers because the TM always returns String.class
    // for getColumnClass()
    // trialPropertiesTable.setDefaultRenderer(TrialLayout.class, new
    // TrialLayoutRenderer(trialPropertiesTableModel));
    // trialPropertiesTable.setDefaultRenderer(PlotIdentOption.class, new
    // PlotIdentOptionRenderer(trialPropertiesTableModel));

    trialPropertiesTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (trialPropertiesTableModel.getRowCount() > 0) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        GuiUtil.initialiseTableColumnWidths(trialPropertiesTable);
                    }
                });
                trialPropertiesTableModel.removeTableModelListener(this);
            }
        }
    });

    //      int tnsColumnIndex = -1;
    //      for (int col = trialPropertiesTableModel.getColumnCount(); --col >= 0; ) {
    //         if (TraitNameStyle.class == trialPropertiesTableModel.getColumnClass(col)) {
    //            tnsColumnIndex = col;
    //            break;
    //         }
    //      }

    editAction.setEnabled(false);
    trialPropertiesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int vrow = trialPropertiesTable.getSelectedRow();
                editAction.setEnabled(vrow >= 0 && trialPropertiesTableModel.isCellEditable(vrow, 1));
            }
        }
    });

    errorMessage.setForeground(Color.RED);
    Box top = Box.createHorizontalBox();
    top.add(errorMessage);
    top.add(Box.createHorizontalGlue());
    top.add(new JButton(editAction));

    JPanel main = new JPanel(new BorderLayout());
    main.add(new JScrollPane(trialPropertiesTable), BorderLayout.CENTER);
    main.add(legendPanel, BorderLayout.SOUTH);

    JScrollPane trialDataTableScrollPane = new JScrollPane(trialDataTable);

    // The preferred height of the viewport is determined
    // by whether or not we need to use hh:mm:ss in the name of any of
    // the scoring data sets.
    JViewport viewPort = new JViewport() {
        @Override
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            d.height = 32;
            TableModel model = trialDataTable.getModel();
            if (model instanceof TrialData) {
                if (((TrialData) model).isUsingHMSformat()) {
                    d.height = 48;
                }
            }
            return d;
        }
    };
    trialDataTableScrollPane.setColumnHeader(viewPort);

    JTableHeader th = trialDataTable.getTableHeader();
    th.setDefaultRenderer(trialDataTableHeaderRenderer);
    th.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int column = th.columnAtPoint(e.getPoint());
            trialDataTableHeaderRenderer.columnSelected = column;
            boolean shifted = 0 != (MouseEvent.SHIFT_MASK & e.getModifiers());
            boolean right = SwingUtilities.isRightMouseButton(e);
            updateDeleteSamplesAction(shifted, right);
            e.consume();
        }
    });

    trialDataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                removeTraitInstancesAction.setEnabled(trialDataTable.getSelectedRowCount() > 0);
            }
        }
    });
    removeTraitInstancesAction.setEnabled(false);

    KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addSampleGroupAction, Msg.TOOLTIP_ADD_SAMPLES_FOR_SCORING());
    KDClientUtils.initAction(ImageId.TRASH_24, deleteSamplesAction, Msg.TOOLTIP_DELETE_COLLECTED_SAMPLES());
    KDClientUtils.initAction(ImageId.EXPORT_24, exportSamplesAction, Msg.TOOLTIP_EXPORT_SAMPLES_OR_TRAITS());
    KDClientUtils.initAction(ImageId.MINUS_GOLD_24, removeTraitInstancesAction,
            Msg.TOOLTIP_REMOVE_TRAIT_INSTANCES_WITH_NO_DATA());

    JPanel trialDataPanel = new JPanel(new BorderLayout());
    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(removeTraitInstancesAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(exportSamplesAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(addSampleGroupAction));
    buttons.add(Box.createHorizontalStrut(8));
    buttons.add(new JButton(deleteSamplesAction));
    trialDataPanel.add(GuiUtil.createLabelSeparator("Measurements by Source", buttons), BorderLayout.NORTH);
    trialDataPanel.add(trialDataTableScrollPane, BorderLayout.CENTER);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, main, trialDataPanel);
    splitPane.setResizeWeight(0.5);

    add(top, BorderLayout.NORTH);
    add(splitPane, BorderLayout.CENTER);

    trialDataTable.setDefaultRenderer(Object.class, new TrialDataCellRenderer());

    trialDataTable.addPropertyChangeListener("model", new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            trialDataTableHeaderRenderer.columnSelected = -1;
            updateDeleteSamplesAction(false, false);
        }
    });
}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createDetailsView() {
    final VFSJFileChooser chooser = getFileChooser();

    JPanel p = new JPanel(new BorderLayout());

    final JTable detailsTable = new JTable(getDetailsTableModel()) {
        // Handle Escape key events here
        @Override//ww w.  j av  a 2  s.  c  o m
        protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if ((e.getKeyCode() == KeyEvent.VK_ESCAPE) && (getCellEditor() == null)) {
                // We are not editing, forward to filechooser.
                chooser.dispatchEvent(e);

                return true;
            }

            return super.processKeyBinding(ks, e, condition, pressed);
        }

        @Override
        public void tableChanged(TableModelEvent e) {
            super.tableChanged(e);

            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                // update header with possibly changed column set
                updateDetailsColumnModel(this);
            }
        }
    };

    //        detailsTable.setRowSorter(getRowSorter());
    detailsTable.setAutoCreateColumnsFromModel(false);
    detailsTable.setComponentOrientation(chooser.getComponentOrientation());
    //detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    detailsTable.setShowGrid(false);
    detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);

    //        detailsTable.addKeyListener(detailsKeyListener);
    Font font = list.getFont();
    detailsTable.setFont(font);
    detailsTable.setIntercellSpacing(new Dimension(0, 0));

    TableCellRenderer headerRenderer = new AlignableTableHeaderRenderer(
            detailsTable.getTableHeader().getDefaultRenderer());
    detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);

    TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
    detailsTable.setDefaultRenderer(Object.class, cellRenderer);

    // So that drag can be started on a mouse press
    detailsTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    detailsTable.addMouseListener(getMouseHandler());
    // No need to addListSelectionListener because selections are forwarded
    // to our JList.

    // 4835633 : tell BasicTableUI that this is a file list
    detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        detailsTable.addFocusListener(repaintListener);
    }

    JTableHeader header = detailsTable.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.addMouseListener(detailsTableModel.new ColumnListener());
    header.setReorderingAllowed(true);

    // TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
    // We don't want them to navigate within the table
    ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
    am.remove("selectNextRowCell");
    am.remove("selectPreviousRowCell");
    am.remove("selectNextColumnCell");
    am.remove("selectPreviousColumnCell");
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);

    JScrollPane scrollpane = new JScrollPane(detailsTable);
    scrollpane.setComponentOrientation(chooser.getComponentOrientation());
    LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");

    // Adjust width of first column so the table fills the viewport when
    // first displayed (temporary listener).
    scrollpane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            JScrollPane sp = (JScrollPane) e.getComponent();
            fixNameColumnWidth(sp.getViewport().getSize().width);
            sp.removeComponentListener(this);
        }
    });

    // 4835633.
    // If the mouse is pressed in the area below the Details view table, the
    // event is not dispatched to the Table MouseListener but to the
    // scrollpane.  Listen for that here so we can clear the selection.
    scrollpane.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            JScrollPane jsp = ((JScrollPane) e.getComponent());
            JTable table = (JTable) jsp.getViewport().getView();

            if (!e.isShiftDown()
                    || (table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) {
                clearSelection();

                TableCellEditor tce = table.getCellEditor();

                if (tce != null) {
                    tce.stopCellEditing();
                }
            }
        }
    });

    detailsTable.setForeground(list.getForeground());
    detailsTable.setBackground(list.getBackground());

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    detailsTableModel.fireTableStructureChanged();

    return p;
}

From source file:com.mirth.connect.client.ui.components.MirthTreeTable.java

@Override
public void setSortable(boolean enable) {
    super.setSortable(enable);

    JTableHeader header = getTableHeader();
    if (enable) {
        if (treeTableSortAdapter == null) {
            treeTableSortAdapter = new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (SwingUtilities.isLeftMouseButton(e)) {
                        JTableHeader h = (JTableHeader) e.getSource();
                        TableColumnModel columnModel = getColumnModel();

                        int viewColumn = h.columnAtPoint(e.getPoint());
                        int column = columnModel.getColumn(viewColumn).getModelIndex();

                        if (column != -1) {
                            beforeSort();

                            // Toggle sort order (ascending <-> descending)
                            SortableTreeTableModel model = (SortableTreeTableModel) getTreeTableModel();
                            model.setColumnAndToggleSortOrder(column);

                            // Set sorting icon and current column index
                            ((SortableHeaderCellRenderer) getTableHeader().getDefaultRenderer())
                                    .setSortingIcon(model.getSortOrder());
                            ((SortableHeaderCellRenderer) getTableHeader().getDefaultRenderer())
                                    .setColumnIndex(column);

                            saveSortPreferences(column);

                            afterSort();
                        }// w w  w  .ja  va  2  s.  c  o  m
                    }
                }
            };
            header.addMouseListener(treeTableSortAdapter);
        }
    } else {
        if (treeTableSortAdapter != null) {
            header.removeMouseListener(treeTableSortAdapter);
            treeTableSortAdapter = null;
        }
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Constructs the pane for the spreadsheet.
 * //from ww  w .jav a2s  . c  o m
 * @param name the name of the pane
 * @param task the owning task
 * @param workbench the workbench to be edited
 * @param showImageView shows image window when first showing the window
 */
public WorkbenchPaneSS(final String name, final Taskable task, final Workbench workbenchArg,
        final boolean showImageView, final boolean isReadOnly) throws Exception {
    super(name, task);

    removeAll();

    if (workbenchArg == null) {
        return;
    }
    this.workbench = workbenchArg;

    this.isReadOnly = isReadOnly;

    headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(headers);

    boolean hasOneOrMoreImages = false;
    // pre load all the data
    for (WorkbenchRow wbRow : workbench.getWorkbenchRows()) {
        for (WorkbenchDataItem wbdi : wbRow.getWorkbenchDataItems()) {
            wbdi.getCellData();
        }

        if (wbRow.getWorkbenchRowImages() != null && wbRow.getWorkbenchRowImages().size() > 0) {
            hasOneOrMoreImages = true;
        }
    }

    model = new GridTableModel(this);
    spreadSheet = new WorkbenchSpreadSheet(model, this);
    spreadSheet.setReadOnly(isReadOnly);
    model.setSpreadSheet(spreadSheet);

    Highlighter simpleStriping = HighlighterFactory.createSimpleStriping();
    GridCellHighlighter hl = new GridCellHighlighter(
            new GridCellPredicate(GridCellPredicate.AnyPredicate, null));
    Short[] errs = { WorkbenchDataItem.VAL_ERROR, WorkbenchDataItem.VAL_ERROR_EDIT };
    ColorHighlighter errColorHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.ValidationPredicate, errs),
            CellRenderingAttributes.errorBackground, null);
    Short[] newdata = { WorkbenchDataItem.VAL_NEW_DATA };
    ColorHighlighter noDataHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.MatchingPredicate, newdata),
            CellRenderingAttributes.newDataBackground, null);
    Short[] multimatch = { WorkbenchDataItem.VAL_MULTIPLE_MATCH };
    ColorHighlighter multiMatchHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.MatchingPredicate, multimatch),
            CellRenderingAttributes.multipleMatchBackground, null);

    spreadSheet.setHighlighters(simpleStriping, hl, errColorHighlighter, noDataHighlighter,
            multiMatchHighlighter);

    //add key mappings for cut, copy, paste
    //XXX Note: these are shortcuts directly to the SpreadSheet cut,copy,paste methods, NOT to the Specify edit menu.
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_C, "Copy", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.cutOrCopy(false);
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_X, "Cut", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.cutOrCopy(true);
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_V, "Paste", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.paste();
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    findPanel = spreadSheet.getFindReplacePanel();
    UIRegistry.getLaunchFindReplaceAction().setSearchReplacePanel(findPanel);

    spreadSheet.setShowGrid(true);
    JTableHeader header = spreadSheet.getTableHeader();
    header.addMouseListener(new ColumnHeaderListener());
    header.setReorderingAllowed(false); // Turn Off column dragging

    // Put the model in image mode, and never change it.
    // Now we're showing/hiding the image column using JXTable's column hiding features.
    model.setInImageMode(true);
    int imageColIndex = model.getColumnCount() - 1;
    imageColExt = spreadSheet.getColumnExt(imageColIndex);
    imageColExt.setVisible(false);

    int sgrColIndex = model.getSgrHeading().getViewOrder();
    sgrColExt = spreadSheet.getColumnExt(sgrColIndex);
    sgrColExt.setComparator(((WorkbenchSpreadSheet) spreadSheet).new NumericColumnComparator());

    int cmpIdx = 0;
    for (Comparator<String> cmp : ((WorkbenchSpreadSheet) spreadSheet).getComparators()) {
        if (cmp != null) {
            spreadSheet.getColumnExt(cmpIdx++).setComparator(cmp);
        }
    }

    // Start off with the SGR score column hidden
    showHideSgrCol(false);

    model.addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            setChanged(true);
        }
    });

    spreadSheet.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            UIRegistry.enableCutCopyPaste(true);
            UIRegistry.enableFind(findPanel, true);
        }

        @Override
        public void focusLost(FocusEvent e) {
            UIRegistry.enableCutCopyPaste(true);
            UIRegistry.enableFind(findPanel, true);
        }
    });

    if (isReadOnly) {
        saveBtn = null;
    } else {
        saveBtn = createButton(getResourceString("SAVE"));
        saveBtn.setToolTipText(
                String.format(getResourceString("WB_SAVE_DATASET_TT"), new Object[] { workbench.getName() }));
        saveBtn.setEnabled(false);
        saveBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                UsageTracker.incrUsageCount("WB.SaveDataSet");

                UIRegistry.writeSimpleGlassPaneMsg(
                        String.format(getResourceString("WB_SAVING"), new Object[] { workbench.getName() }),
                        WorkbenchTask.GLASSPANE_FONT_SIZE);
                UIRegistry.getStatusBar().setIndeterminate(workbench.getName(), true);
                final SwingWorker worker = new SwingWorker() {
                    @SuppressWarnings("synthetic-access")
                    @Override
                    public Object construct() {
                        try {
                            saveObject();

                        } catch (Exception ex) {
                            UsageTracker.incrHandledUsageCount();
                            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class,
                                    ex);
                            log.error(ex);
                            return ex;
                        }
                        return null;
                    }

                    // Runs on the event-dispatching thread.
                    @Override
                    public void finished() {
                        Object retVal = get();
                        if (retVal != null && retVal instanceof Exception) {
                            Exception ex = (Exception) retVal;
                            UIRegistry.getStatusBar().setErrorMessage(getResourceString("WB_ERROR_SAVING"), ex);
                        }

                        UIRegistry.clearSimpleGlassPaneMsg();
                        UIRegistry.getStatusBar().setProgressDone(workbench.getName());
                    }
                };
                worker.start();

            }
        });
    }

    Action delAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_F3, "DelRow", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            if (validationWorkerQueue.peek() == null) {
                deleteRows();
            }
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    if (isReadOnly) {
        deleteRowsBtn = null;
    } else {
        deleteRowsBtn = createIconBtn("DelRec", "WB_DELETE_ROW", delAction);
        selectionSensitiveButtons.add(deleteRowsBtn);
        spreadSheet.setDeleteAction(delAction);
    }

    //XXX Using the wb ID in the prefname to do pref setting per wb, may result in a bloated prefs file?? 
    doIncrementalValidation = AppPreferences.getLocalPrefs()
            .getBoolean(wbAutoValidatePrefName + "." + workbench.getId(), true);
    doIncrementalMatching = AppPreferences.getLocalPrefs()
            .getBoolean(wbAutoMatchPrefName + "." + workbench.getId(), false);

    if (isReadOnly) {
        clearCellsBtn = null;
    } else {
        clearCellsBtn = createIconBtn("Eraser", "WB_CLEAR_CELLS", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                spreadSheet.clearSorter();

                if (spreadSheet.getCellEditor() != null) {
                    spreadSheet.getCellEditor().stopCellEditing();
                }
                int[] rows = spreadSheet.getSelectedRowModelIndexes();
                int[] cols = spreadSheet.getSelectedColumnModelIndexes();
                model.clearCells(rows, cols);
            }
        });
        selectionSensitiveButtons.add(clearCellsBtn);
    }

    Action addAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_N, "AddRow", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            if (workbench.getWorkbenchRows().size() < WorkbenchTask.MAX_ROWS) {
                if (validationWorkerQueue.peek() == null) {
                    addRowAfter();
                }
            }
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    if (isReadOnly) {
        addRowsBtn = null;
    } else {
        addRowsBtn = createIconBtn("AddRec", "WB_ADD_ROW", addAction);
        addRowsBtn.setEnabled(true);
        addAction.setEnabled(true);
    }

    if (isReadOnly) {
        carryForwardBtn = null;
    } else {
        carryForwardBtn = createIconBtn("CarryForward20x20", IconManager.IconSize.NonStd, "WB_CARRYFORWARD",
                false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        UsageTracker.getUsageCount("WBCarryForward");

                        configCarryFoward();
                    }
                });
        carryForwardBtn.setEnabled(true);
    }

    toggleImageFrameBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    toggleImageFrameVisible();
                }
            });
    toggleImageFrameBtn.setEnabled(true);

    importImagesBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    toggleImportImageFrameVisible();
                }
            });
    importImagesBtn.setEnabled(true);

    /*showMapBtn = createIconBtn("ShowMap", IconManager.IconSize.NonStd, "WB_SHOW_MAP", false, new ActionListener()
    {
    public void actionPerformed(ActionEvent ae)
    {
        showMapOfSelectedRecords();
    }
    });*/
    // enable or disable along with Google Earth and Geo Ref Convert buttons

    if (isReadOnly) {
        exportKmlBtn = null;
    } else {
        exportKmlBtn = createIconBtn("GoogleEarth", IconManager.IconSize.NonStd, "WB_SHOW_IN_GOOGLE_EARTH",
                false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                showRecordsInGoogleEarth();
                            }
                        });
                    }
                });
    }

    // 

    readRegisteries();

    // enable or disable along with Show Map and Geo Ref Convert buttons

    if (isReadOnly) {
        geoRefToolBtn = null;
    } else {
        AppPreferences remotePrefs = AppPreferences.getRemote();
        final String tool = remotePrefs.get("georef_tool", "geolocate");
        String iconName = "GEOLocate20"; //tool.equalsIgnoreCase("geolocate") ? "GeoLocate" : "BioGeoMancer";
        String toolTip = tool.equalsIgnoreCase("geolocate") ? "WB_DO_GEOLOCATE_LOOKUP"
                : "WB_DO_BIOGEOMANCER_LOOKUP";
        geoRefToolBtn = createIconBtn(iconName, IconManager.IconSize.NonStd, toolTip, false,
                new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        spreadSheet.clearSorter();

                        if (tool.equalsIgnoreCase("geolocate")) {
                            doGeoRef(new edu.ku.brc.services.geolocate.prototype.GeoCoordGeoLocateProvider(),
                                    "WB.GeoLocateRows");
                        } else {
                            doGeoRef(new GeoCoordBGMProvider(), "WB.BioGeomancerRows");
                        }
                    }
                });
        // only enable it if the workbench has the proper columns in it
        String[] missingColumnsForBG = getMissingButRequiredColumnsForGeoRefTool(tool);
        if (missingColumnsForBG.length > 0) {
            geoRefToolBtn.setEnabled(false);
            String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>";
            for (String reqdField : missingColumnsForBG) {
                ttText += "<li>" + reqdField + "</li>";
            }
            ttText += "</ul>";
            String origTT = geoRefToolBtn.getToolTipText();
            geoRefToolBtn.setToolTipText("<html>" + origTT + ttText);
        } else {
            geoRefToolBtn.setEnabled(true);
        }
    }

    if (isReadOnly) {
        convertGeoRefFormatBtn = null;
    } else {
        convertGeoRefFormatBtn = createIconBtn("ConvertGeoRef", IconManager.IconSize.NonStd,
                "WB_CONVERT_GEO_FORMAT", false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        showGeoRefConvertDialog();
                    }
                });

        // now enable/disable the geo ref related buttons
        String[] missingGeoRefFields = getMissingGeoRefLatLonFields();
        if (missingGeoRefFields.length > 0) {
            convertGeoRefFormatBtn.setEnabled(false);
            exportKmlBtn.setEnabled(false);
            //showMapBtn.setEnabled(false);

            String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>";
            for (String reqdField : missingGeoRefFields) {
                ttText += "<li>" + reqdField + "</li>";
            }
            ttText += "</ul>";
            String origTT1 = convertGeoRefFormatBtn.getToolTipText();
            convertGeoRefFormatBtn.setToolTipText("<html>" + origTT1 + ttText);
            String origTT2 = exportKmlBtn.getToolTipText();
            exportKmlBtn.setToolTipText("<html>" + origTT2 + ttText);
            //String origTT3 = showMapBtn.getToolTipText();
            //showMapBtn.setToolTipText("<html>" + origTT3 + ttText);
        } else {
            convertGeoRefFormatBtn.setEnabled(true);
            exportKmlBtn.setEnabled(true);
            //showMapBtn.setEnabled(true);
        }
    }

    if (AppContextMgr.isSecurityOn() && !task.getPermissions().canModify()) {
        exportExcelCsvBtn = null;
    } else {
        exportExcelCsvBtn = createIconBtn("Export", IconManager.IconSize.NonStd, "WB_EXPORT_DATA", false,
                new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        doExcelCsvExport();
                    }
                });
        exportExcelCsvBtn.setEnabled(true);
    }

    uploadDatasetBtn = createIconBtn("Upload", IconManager.IconSize.Std24, "WB_UPLOAD_DATA", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    doDatasetUpload();
                }
            });
    uploadDatasetBtn.setVisible(isUploadPermitted() && !UIRegistry.isMobile());
    uploadDatasetBtn.setEnabled(canUpload());
    if (!uploadDatasetBtn.isEnabled()) {
        uploadDatasetBtn.setToolTipText(getResourceString("WB_UPLOAD_IN_PROGRESS"));
    }

    // listen to selection changes to enable/disable certain buttons
    spreadSheet.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                JStatusBar statusBar = UIRegistry.getStatusBar();
                statusBar.setText("");

                currentRow = spreadSheet.getSelectedRow();
                updateBtnUI();
            }
        }
    });

    for (int c = 0; c < spreadSheet.getTableHeader().getColumnModel().getColumnCount(); c++) {
        // TableColumn column =
        // spreadSheet.getTableHeader().getColumnModel().getColumn(spreadSheet.getTableHeader().getColumnModel().getColumnCount()-1);
        TableColumn column = spreadSheet.getTableHeader().getColumnModel().getColumn(c);
        column.setCellRenderer(new WbCellRenderer());
    }

    // setup the JFrame to show images attached to WorkbenchRows
    imageFrame = new ImageFrame(mapSize, this, this.workbench, task, isReadOnly);

    // setup the JFrame to show images attached to WorkbenchRows
    imageImportFrame = new ImageImportFrame(this, this.workbench);

    setupWorkbenchRowChangeListener();

    // setup window minimizing/maximizing listener
    JFrame topFrame = (JFrame) UIRegistry.getTopWindow();
    minMaxWindowListener = new WindowAdapter() {
        @Override
        public void windowDeiconified(WindowEvent e) {
            if (imageFrame != null && imageFrame.isVisible()) {
                imageFrame.setExtendedState(Frame.NORMAL);
            }
            if (mapFrame != null && mapFrame.isVisible()) {
                mapFrame.setExtendedState(Frame.NORMAL);
            }
        }

        @Override
        public void windowIconified(WindowEvent e) {
            if (imageFrame != null && imageFrame.isVisible()) {
                imageFrame.setExtendedState(Frame.ICONIFIED);
            }
            if (mapFrame != null && mapFrame.isVisible()) {
                mapFrame.setExtendedState(Frame.ICONIFIED);
            }
        }
    };
    topFrame.addWindowListener(minMaxWindowListener);

    if (!isReadOnly) {
        showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd,
                "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        if (uploadToolPanel.isExpanded()) {
                            hideUploadToolPanel();
                            showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL"));
                        } else {
                            showUploadToolPanel();
                            showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL"));
                        }
                    }
                });
        showHideUploadToolBtn.setEnabled(true);
    }

    // setup the mapping features
    mapFrame = new JFrame();
    mapFrame.setIconImage(IconManager.getImage("AppIcon").getImage());
    mapFrame.setTitle(getResourceString("WB_GEO_REF_DATA_MAP"));
    mapImageLabel = createLabel("");
    mapImageLabel.setSize(500, 500);
    mapFrame.add(mapImageLabel);
    mapFrame.setSize(500, 500);

    // start putting together the visible UI
    CellConstraints cc = new CellConstraints();

    JComponent[] compsArray = { addRowsBtn, deleteRowsBtn, clearCellsBtn, /*showMapBtn,*/ exportKmlBtn,
            geoRefToolBtn, convertGeoRefFormatBtn, exportExcelCsvBtn, uploadDatasetBtn, showHideUploadToolBtn };
    Vector<JComponent> availableComps = new Vector<JComponent>(
            compsArray.length + workBenchPluginSSBtns.size());
    for (JComponent c : compsArray) {
        if (c != null) {
            availableComps.add(c);
        }
    }
    for (JComponent c : workBenchPluginSSBtns) {
        availableComps.add(c);
    }

    PanelBuilder spreadSheetControlBar = new PanelBuilder(new FormLayout(
            "f:p:g,4px," + createDuplicateJGoodiesDef("p", "4px", availableComps.size()) + ",4px,", "c:p:g"));

    int x = 3;
    for (JComponent c : availableComps) {
        spreadSheetControlBar.add(c, cc.xy(x, 1));
        x += 2;
    }

    int h = 0;
    Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>();
    headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(headers);
    for (WorkbenchTemplateMappingItem mi : headers) {
        //using the workbench data model table. Not the actual specify table the column is mapped to.
        //This MIGHT be less confusing
        //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); 
        spreadSheet.getColumnModel().getColumn(h++)
                .setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName()));
    }

    // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes.
    initColumnSizes(spreadSheet, saveBtn);

    // Create the Form Pane  -- needs to be done after initColumnSizes - which also sets cell editors for collumns
    if (task instanceof SGRTask) {
        formPane = new SGRFormPane(this, workbench, isReadOnly);
    } else {
        formPane = new FormPane(this, workbench, isReadOnly);
    }

    // This panel contains just the ResultSetContoller, it's needed so the RSC gets centered
    PanelBuilder rsPanel = new PanelBuilder(new FormLayout("c:p:g", "c:p:g"));
    FormValidator dummy = new FormValidator(null);
    dummy.setEnabled(true);
    resultsetController = new ResultSetController(dummy, !isReadOnly, !isReadOnly, false,
            getResourceString("Record"), model.getRowCount(), true);
    resultsetController.addListener(formPane);
    if (!isReadOnly) {
        resultsetController.getDelRecBtn().addActionListener(delAction);
    }
    //        else
    //        {
    //            resultsetController.getDelRecBtn().setVisible(false);
    //        }
    rsPanel.add(resultsetController.getPanel(), cc.xy(1, 1));

    // This panel is a single row containing the ResultSetContoller and the other controls for the Form Panel
    String colspec = "f:p:g, p, f:p:g, p";
    for (int i = 0; i < workBenchPluginFormBtns.size(); i++) {
        colspec = colspec + ", f:p, p";
    }

    PanelBuilder resultSetPanel = new PanelBuilder(new FormLayout(colspec, "c:p:g"));
    // Now put the two panel into the single row panel
    resultSetPanel.add(rsPanel.getPanel(), cc.xy(2, 1));
    if (!isReadOnly) {
        resultSetPanel.add(formPane.getControlPropsBtn(), cc.xy(4, 1));
    }
    int ccx = 6;
    for (JComponent c : workBenchPluginFormBtns) {
        resultSetPanel.add(c, cc.xy(ccx, 1));
        ccx += 2;
    }

    // Create the main panel that uses card layout for the form and spreasheet
    mainPanel = new JPanel(cardLayout = new CardLayout());

    // Add the Form and Spreadsheet to the CardLayout
    mainPanel.add(spreadSheet.getScrollPane(), PanelType.Spreadsheet.toString());
    mainPanel.add(formPane.getPane(), PanelType.Form.toString());

    // The controllerPane is a CardLayout that switches between the Spreadsheet control bar and the Form Control Bar
    controllerPane = new JPanel(cpCardLayout = new CardLayout());
    controllerPane.add(spreadSheetControlBar.getPanel(), PanelType.Spreadsheet.toString());
    controllerPane.add(resultSetPanel.getPanel(), PanelType.Form.toString());

    JLabel sep1 = new JLabel(IconManager.getIcon("Separator"));
    JLabel sep2 = new JLabel(IconManager.getIcon("Separator"));
    ssFormSwitcher = createSwitcher();

    // This works
    setLayout(new BorderLayout());

    boolean doDnDImages = AppPreferences.getLocalPrefs().getBoolean("WB_DND_IMAGES", false);
    JComponent[] ctrlCompArray1 = { importImagesBtn, toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2,
            ssFormSwitcher };
    JComponent[] ctrlCompArray2 = { toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher };
    JComponent[] ctrlCompArray = doDnDImages ? ctrlCompArray1 : ctrlCompArray2;

    Vector<Pair<JComponent, Integer>> ctrlComps = new Vector<Pair<JComponent, Integer>>();
    for (JComponent c : ctrlCompArray) {
        ctrlComps.add(new Pair<JComponent, Integer>(c, null));
    }

    String layoutStr = "";
    int compCount = 0;
    int col = 1;
    int pos = 0;
    for (Pair<JComponent, Integer> c : ctrlComps) {
        JComponent comp = c.getFirst();
        if (comp != null) {
            boolean addComp = !(comp == sep1 || comp == sep2) || compCount > 0;
            if (!addComp) {
                c.setFirst(null);
            } else {
                if (!StringUtils.isEmpty(layoutStr)) {
                    layoutStr += ",";
                    col++;
                    if (pos < ctrlComps.size() - 1) {
                        //this works because we know ssFormSwitcher is last and always non-null.
                        layoutStr += "6px,";
                        col++;
                    }
                }
                c.setSecond(col);
                if (comp == sep1 || comp == sep2) {
                    layoutStr += "6px";
                    compCount = 0;
                } else {
                    layoutStr += "p";
                    compCount++;
                }
            }
        }
        pos++;
    }
    PanelBuilder ctrlBtns = new PanelBuilder(new FormLayout(layoutStr, "c:p:g"));
    for (Pair<JComponent, Integer> c : ctrlComps) {
        if (c.getFirst() != null) {
            ctrlBtns.add(c.getFirst(), cc.xy(c.getSecond(), 1));
        }
    }

    add(mainPanel, BorderLayout.CENTER);

    FormLayout formLayout = new FormLayout("f:p:g,4px,p", "2px,f:p:g,p:g,p:g");
    PanelBuilder builder = new PanelBuilder(formLayout);

    builder.add(controllerPane, cc.xy(1, 2));
    builder.add(ctrlBtns.getPanel(), cc.xy(3, 2));

    if (!isReadOnly) {
        uploadToolPanel = new UploadToolPanel(this, UploadToolPanel.EXPANDED);
        uploadToolPanel.createUI();
        //            showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener()
        //            {
        //                public void actionPerformed(ActionEvent ae)
        //                {
        //                    if (uploadToolPanel.isExpanded())
        //                    {
        //                       hideUploadToolPanel();
        //                       showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL"));
        //                    } else
        //                    {
        //                       showUploadToolPanel();
        //                       showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL"));
        //                   }
        //                }
        //            });
        //            showHideUploadToolBtn.setEnabled(true);
    }

    builder.add(uploadToolPanel, cc.xywh(1, 3, 3, 1));
    builder.add(findPanel, cc.xywh(1, 4, 3, 1));

    add(builder.getPanel(), BorderLayout.SOUTH);

    resultsetController.addListener(new ResultSetControllerListener() {
        public boolean indexAboutToChange(int oldIndex, int newIndex) {
            return true;
        }

        public void indexChanged(int newIndex) {
            if (imageFrame != null) {
                if (newIndex > -1) {
                    int index = spreadSheet.convertRowIndexToModel(newIndex);
                    imageFrame.setRow(workbench.getRow(index));
                } else {
                    imageFrame.setRow(null);
                }
            }
        }

        public void newRecordAdded() {
            // do nothing
        }
    });
    //compareSchemas();
    if (getIncremental() && workbenchValidator == null) {
        buildValidator();
    }

    //        int c = 0;
    //        Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>();
    //        headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    //        Collections.sort(headers);
    //        for (WorkbenchTemplateMappingItem mi : headers)
    //        {
    //           //using the workbench data model table. Not the actual specify table the column is mapped to.
    //           //This MIGHT be less confusing
    //           //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); 
    //           spreadSheet.getColumnModel().getColumn(c++).setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName()));
    //        }
    //        
    //        // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes.
    //        initColumnSizes(spreadSheet, saveBtn);

    // See if we need to make the Image Frame visible
    // Commenting this out for now because it is so annoying.

    if (showImageView || hasOneOrMoreImages) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                toggleImageFrameVisible();

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        final Frame f = (Frame) UIRegistry.get(UIRegistry.FRAME);
                        f.toFront();
                        f.requestFocus();
                    }
                });
            }
        });
    }

    ((WorkbenchTask) ContextMgr.getTaskByClass(WorkbenchTask.class)).opening(this);
    ((SGRTask) ContextMgr.getTaskByClass(SGRTask.class)).opening(this);
}

From source file:net.sourceforge.pmd.cpd.GUI.java

private JComponent makeMatchList() {

    resultsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override//from   w  w  w  .  j a v  a  2 s.c om
        public void valueChanged(ListSelectionEvent e) {
            populateResultArea();
        }
    });

    resultsTable.registerKeyboardAction(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            copyMatchListSelectionsToClipboard();
        }
    }, "Copy", COPY_KEY_STROKE, JComponent.WHEN_FOCUSED);

    resultsTable.registerKeyboardAction(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            deleteMatchlistSelections();
        }
    }, "Del", DELETE_KEY_STROKE, JComponent.WHEN_FOCUSED);

    int[] alignments = new int[matchColumns.length];
    for (int i = 0; i < alignments.length; i++) {
        alignments[i] = matchColumns[i].alignment();
    }

    resultsTable.setDefaultRenderer(Object.class, new AlignmentRenderer(alignments));

    final JTableHeader header = resultsTable.getTableHeader();
    header.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            sortOnColumn(header.columnAtPoint(new Point(e.getX(), e.getY())));
        }
    });

    return new JScrollPane(resultsTable);
}

From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java

/**
 * Setup the JTable with its desired characteristics
 *//*from  w  w  w. j  av a  2s  .  c om*/
private void setupTable() {
    table = new CustomTable(spreadsheetModel);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);
    table.setShowVerticalLines(true);
    table.setShowHorizontalLines(true);
    table.setGridColor(UIHelper.LIGHT_GREEN_COLOR);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setAutoCreateColumnsFromModel(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.getSelectionModel().addListSelectionListener(this);
    table.getColumnModel().getSelectionModel().addListSelectionListener(this);
    table.getTableHeader().setReorderingAllowed(true);
    table.getColumnModel().addColumnModelListener(this);
    try {
        table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer());
    } catch (ClassNotFoundException e) {
        // ignore this error
    }

    table.addMouseListener(this);
    table.getTableHeader().addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent event) {
        }

        public void mouseMoved(MouseEvent event) {
            // display a tooltip when user hovers over a column. tooltip is derived
            // from the description of a field from the TableReferenceObject.
            JTable table = ((JTableHeader) event.getSource()).getTable();
            TableColumnModel colModel = table.getColumnModel();
            int colIndex = colModel.getColumnIndexAtX(event.getX());

            // greater than 1 to account for the row no. being the first col
            if (colIndex >= 1) {
                TableColumn tc = colModel.getColumn(colIndex);
                if (tc != null) {
                    try {
                        table.getTableHeader().setToolTipText(getFieldDescription(tc));
                    } catch (Exception e) {
                        // ignore this error
                    }
                }
            }
        }
    });

    //table.getColumnModel().addColumnModelListener(this);
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);

    //  Override the default tab behaviour
    //  Tab to the next editable cell. When no editable cells goto next cell.
    final Action previousTabAction = table.getActionMap().get(im.get(tab));
    Action newTabAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // maintain previous tab action procedure
            previousTabAction.actionPerformed(e);

            JTable table = (JTable) e.getSource();
            int row = table.getSelectedRow();
            int originalRow = row;
            int column = table.getSelectedColumn();
            int originalColumn = column;

            while (!table.isCellEditable(row, column)) {
                previousTabAction.actionPerformed(e);
                row = table.getSelectedRow();
                column = table.getSelectedColumn();

                //  Back to where we started, get out.
                if ((row == originalRow) && (column == originalColumn)) {
                    break;
                }
            }

            if (table.editCellAt(row, column)) {
                table.getEditorComponent().requestFocusInWindow();
            }
        }
    };

    table.getActionMap().put(im.get(tab), newTabAction);
    TableColumnModel model = table.getColumnModel();

    String previousColumnName = null;
    for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) {
        if (!model.getColumn(columnIndex).getHeaderValue().toString()
                .equals(TableReferenceObject.ROW_NO_TEXT)) {
            model.getColumn(columnIndex).setHeaderRenderer(columnRenderer);
            model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions
                    .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString()));
            // add appropriate cell editor for cell.
            spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName);
            previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString();
        } else {
            model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer());
        }
    }

    JTableHeader header = table.getTableHeader();
    header.setBackground(UIHelper.BG_COLOR);
    header.addMouseListener(new HeaderListener(header, columnRenderer));

    table.addNotify();
}

From source file:org.svv.acmate.gui.ACTestingPanel.java

@Override
public void startURLChanged() {
    pageModel = new PageTableModel(siteMap);
    tblSelectPages.setModel(pageModel);/* www.  j a  v a2  s .  c o  m*/

    JTableHeader header = tblSelectPages.getTableHeader();
    header.addMouseListener(new TableHeaderMouseListener(tblSelectPages, 0));
}

From source file:org.svv.acmate.gui.ACTestingPanel.java

@Override
public void configReloaded() {
    userModel = new ActiveUserTableModel(model);
    tblSelectUsers.setModel(userModel);//ww w. j a v  a2  s  .co m

    JTableHeader header = tblSelectUsers.getTableHeader();
    header.addMouseListener(new TableHeaderMouseListener(tblSelectUsers, 1));

    resizeColumnWidth(tblSelectUsers);

    Authentication authentication = model.getConfigModel().getAuthentication();
    if (authentication != null) {
        txtLoginURL.setText(authentication.getLogInURL());
        txtLogOutSubfix.setText(authentication.getLogoutURLSubfix());
        if (authentication.getMethod() != null) {
            String authenMethod = authentication.getMethod().value();
            if (authenMethod != null)
                cboLoginType.setSelectedItem(authenMethod);
        }
    }
}

From source file:org.ut.biolab.medsavant.client.view.genetics.variantinfo.VariantFrequencyAggregatePane.java

public void setVariantRecords(Set<VariantRecord> records) {
    innerPanel.removeAll();/*  w  w  w .j  a  va  2s  .  c  om*/
    //This function executes quickly, no need for waitPanel.
    //innerPanel.add(new WaitPanel("Loading DNA Ids..."));
    tableModel.setValues(records);
    aggregateTable = new AggregateTable(tableModel) {
        @Override
        //Necessary to enable buttons within the table.
        public boolean isCellEditable(int rowIndex, int colIndex) {
            return colIndex == buttonIndex;
        }

        //"Disables" selection within the aggregateTable.
        @Override
        public TableCellRenderer getCellRenderer(final int rowIndex, final int columnIndex) {
            final TableCellRenderer renderer = super.getCellRenderer(rowIndex, columnIndex);
            return new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable jtable, final Object o, boolean bln,
                        boolean bln1, int i, int i1) {
                    return renderer.getTableCellRendererComponent(jtable, o, false, false, i, i1);
                }
            };
        }

        //This overridden method, together with the custom mouse listener on the 
        //AggregateTable header, disallows moving the first column, and columns
        //>= dnaIDIndex                    
        @Override
        protected AggregateTable.DraggingHandler createDraggingColumnPropertyChangeListener() {
            return new AggregateTable.DraggingHandler() {
                @Override
                public void columnMoved(TableColumnModelEvent e) {
                    if (fromColumnIndex == -1) {
                        fromColumnIndex = e.getFromIndex();
                    }
                    toColumnIndex = e.getToIndex();
                }

            };
        }
    };

    header = new AggregateTableHeader(aggregateTable);
    header.addMouseListener(new MouseAdapter() {
        //Disable moving the first column, or columns with index
        //>=dnaIDIndex
        @Override
        public void mouseReleased(MouseEvent e) {
            if (toColumnIndex != -1 && ((toColumnIndex == 0 || fromColumnIndex == 0)
                    || (toColumnIndex >= dnaIDIndex || fromColumnIndex >= dnaIDIndex))) {
                aggregateTable.moveColumn(toColumnIndex, fromColumnIndex);
                String msg = "This column cannot be moved.";
                DialogUtils.displayMessage(msg);
            } else {
                for (int columnHeaderIndex = 0; columnHeaderIndex < header.getColumnModel().getColumnCount()
                        - 2; columnHeaderIndex++) {
                    String columnTitle = (String) header.getColumnModel().getColumn(columnHeaderIndex)
                            .getHeaderValue();
                    aggregateColumns[columnHeaderIndex] = columnTitle;
                }
                reaggregate();
            }
            //aggregateTable.aggregate(this.aggregateColumns);
            fromColumnIndex = -1;
            toColumnIndex = -1;
            //expandAllButLast();
        }
    });

    header.setAutoFilterEnabled(false);
    header.setReorderingAllowed(true);
    header.setFont(TABLE_FONT_LARGE);
    aggregateTable.setTableHeader(header);
    aggregateTable.setAutoResizeMode(AggregateTable.AUTO_RESIZE_ALL_COLUMNS);
    aggregateTable.setFont(TABLE_FONT_LARGE);

    //Setup a custom "summary".  This is what calculates frequencies when cells are
    //collapsed
    PivotField f = aggregateTable.getAggregateTableModel().getField(BasicVariantColumns.DNA_ID.getAlias());
    f.setSummaryType(PivotConstants.SUMMARY_RESERVED_MAX + 1);
    aggregateTable.getAggregateTableModel().setSummaryCalculator(new SummaryCalculator() {
        private Set<String> collapsedDNAIDs = new HashSet<String>();
        private Values lastRowValues;
        private int valueCount = 0;
        private final int SUMMARY_FREQ = PivotConstants.SUMMARY_RESERVED_MAX + 1;

        @Override
        public void addValue(PivotValueProvider dataModel, PivotField field, Values rowValues,
                Values columnValues, Object object) {
            //this gets called multiple times for all the cells that disappear when 
            //something is collapsed.  
            // row[0] is the value of the corresponding first column: e.g. a Cohort or Family. 
            // columnValues can be ignored (blank)
            // Object is the value of the item in the cell that disappeared. (i.e. those cells which are being summarized)
            // field.getName() is the column name corresponding to Object

            // Useful Debugging code:                      
            //if(field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())){

            /*
             System.out.println("==========");
             System.out.println("Field : " + field.getName());
             System.out.println("Row values: ");
                    
             for (int i = 0; i < rowValues.getCount(); ++i) {
             System.out.println("\trow[" + i + "] = " + rowValues.getValueAt(i).getValue());
                    
             }
                    
             System.out.println("Column values: ");
             for (int i = 0; i < columnValues.getCount(); ++i) {
             System.out.println("\tcol[" + i + "] = " + columnValues.getValueAt(i).getValue());
             }
                    
             System.out.println("Object: ");
             System.out.println("\t" + object);
             System.out.println("==========");
             */

            // }
            if (field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())) {
                collapsedDNAIDs.add((String) object);
                lastRowValues = rowValues;
            } else {
                lastRowValues = null;
            }
            valueCount++;
        }

        //Should never be called
        @Override
        public void addValue(Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (1)");
        }

        //Should never be called
        @Override
        public void addValue(IPivotDataModel ipdm, PivotField pf, int i, int i1, Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (2)");
        }

        //Should never be called
        @Override
        public void addValue(PivotValueProvider pvp, PivotField pf, Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (3)");
        }

        @Override
        public void clear() {
            collapsedDNAIDs.clear();
            valueCount = 0;
            lastRowValues = null;
        }

        @Override
        public Object getSummaryResult(int type) {
            //if null, then we're not in the DNAId column.  Return null
            //to show a blank in this cell
            if (lastRowValues == null) {
                return null;
            }

            int numIndividuals = getNumberOfIndividualsInGroup(lastRowValues.getValueAt(0));

            return new Frequency(collapsedDNAIDs.size(), numIndividuals);
        }

        private int getNumberOfIndividualsInGroup(Value v) {
            if (aggregateColumns[0].equals("Cohort")) {
                //LOG.debug("Getting number of individuals in group " + v.getValue());
                Set<String> dnaIds = cohortDNAIDMap.get((Cohort) v.getValue());
                //for (String id : dnaIds) {
                //LOG.debug("\tGot id " + id);
                //}
                return cohortDNAIDMap.get((Cohort) v.getValue()).size();
            } else if (aggregateColumns[0].equals(BasicPatientColumns.FAMILY_ID.getAlias())) {
                return familyIDdnaIDMap.get((String) v.getValue()).size();
            } else {
                LOG.error("Invalid first column");
                return -1;
            }
        }

        @Override
        public long getCount() {
            return valueCount;
        }

        @Override
        public int getNumberOfSummaries() {
            return 1;
        }

        @Override
        public String getSummaryName(Locale locale, int i) {
            return "Frequency";
        }

        @Override
        public int[] getAllowedSummaries(Class<?> type) {
            return new int[] { SUMMARY_FREQ };
        }

        @Override
        public int[] getAllowedSummaries(Class<?> type, ConverterContext cc) {
            return new int[] { SUMMARY_FREQ };
        }
    });

    //Sets up the context menu for clicking column headers.  This will probably not be used
    //frequently.  Limit the available operations to collapsing, expanding, and grouping.
    TableHeaderPopupMenuInstaller installer = new TableHeaderPopupMenuInstaller(aggregateTable);
    installer.addTableHeaderPopupMenuCustomizer(new AggregateTablePopupMenuCustomizer() {
        @Override
        public void customizePopupMenu(JTableHeader header, JPopupMenu popup, int clickingColumn) {
            super.customizePopupMenu(header, popup, clickingColumn);
            for (int i = 0; i < popup.getComponentCount(); i++) {
                String menuItemName = popup.getComponent(i).getName();
                if (!(CONTEXT_MENU_COLLAPSE.equals(menuItemName)
                        || CONTEXT_MENU_COLLAPSE_ALL.equals(menuItemName)
                        || CONTEXT_MENU_EXPAND.equals(menuItemName)
                        || CONTEXT_MENU_EXPAND_ALL.equals(menuItemName)
                        || CONTEXT_MENU_GROUP.equals(menuItemName)
                        || CONTEXT_MENU_UNGROUP.equals(menuItemName))) {

                    popup.remove(popup.getComponent(i));

                }
            }
        }
    });

    aggregateTable.getAggregateTableModel().setSummaryMode(true);

    aggregateTable.aggregate(aggregateColumns);
    aggregateTable.setShowContextMenu(false);

    expandAllButLast();
    setupButtonColumn();

    JScrollPane jsp = new JScrollPane(aggregateTable);
    jsp.setPreferredSize(PREFERRED_SIZE);

    JPanel bp = new JPanel();

    bp.setLayout(new BoxLayout(bp, BoxLayout.X_AXIS));
    JButton closeButton = new JButton(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.CLOSE));
    closeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            unsplitScreen();
        }
    });
    bp.add(Box.createHorizontalGlue());
    bp.add(title);
    bp.add(Box.createHorizontalGlue());
    bp.add(closeButton);
    innerPanel.add(bp);
    innerPanel.add(jsp);
    reaggregate();
    innerPanel.revalidate();
    innerPanel.repaint();
}