Example usage for javax.swing.event ListSelectionListener ListSelectionListener

List of usage examples for javax.swing.event ListSelectionListener ListSelectionListener

Introduction

In this page you can find the example usage for javax.swing.event ListSelectionListener ListSelectionListener.

Prototype

ListSelectionListener

Source Link

Usage

From source file:com.mirth.connect.connectors.http.HttpListener.java

public void setResponseHeaders(Map<String, List<String>> responseHeaders) {
    int size = 0;
    for (List<String> property : responseHeaders.values()) {
        size += property.size();/*ww  w .j  av  a 2  s  . com*/
    }

    Object[][] tableData = new Object[size][2];

    responseHeadersTable = new MirthTable();

    int j = 0;
    Iterator i = responseHeaders.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        for (String keyValue : (List<String>) entry.getValue()) {
            tableData[j][NAME_COLUMN] = (String) entry.getKey();
            tableData[j][VALUE_COLUMN] = keyValue;
            j++;
        }
    }

    responseHeadersTable.setModel(new javax.swing.table.DefaultTableModel(tableData,
            new String[] { NAME_COLUMN_NAME, VALUE_COLUMN_NAME }) {

        boolean[] canEdit = new boolean[] { true, true };

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    });

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

        public void valueChanged(ListSelectionEvent evt) {
            if (getSelectedRow(responseHeadersTable) != -1) {
                responseHeadersLastIndex = getSelectedRow(responseHeadersTable);
                responseHeadersDeleteButton.setEnabled(true);
            } else {
                responseHeadersDeleteButton.setEnabled(false);
            }
        }
    });

    class HTTPTableCellEditor extends TextFieldCellEditor {

        boolean checkProperties;

        public HTTPTableCellEditor(boolean checkProperties) {
            super();
            this.checkProperties = checkProperties;
        }

        @Override
        public boolean isCellEditable(EventObject evt) {
            boolean editable = super.isCellEditable(evt);

            if (editable) {
                responseHeadersDeleteButton.setEnabled(false);
            }

            return editable;
        }

        @Override
        protected boolean valueChanged(String value) {
            responseHeadersDeleteButton.setEnabled(true);

            if (checkProperties && (value.length() == 0)) {
                return false;
            }

            parent.setSaveEnabled(true);
            return true;
        }
    }

    responseHeadersTable.getColumnModel()
            .getColumn(responseHeadersTable.getColumnModel().getColumnIndex(NAME_COLUMN_NAME))
            .setCellEditor(new HTTPTableCellEditor(true));
    responseHeadersTable.getColumnModel()
            .getColumn(responseHeadersTable.getColumnModel().getColumnIndex(VALUE_COLUMN_NAME))
            .setCellEditor(new HTTPTableCellEditor(false));
    responseHeadersTable.setCustomEditorControls(true);

    responseHeadersTable.setSelectionMode(0);
    responseHeadersTable.setRowSelectionAllowed(true);
    responseHeadersTable.setRowHeight(UIConstants.ROW_HEIGHT);
    responseHeadersTable.setDragEnabled(false);
    responseHeadersTable.setOpaque(true);
    responseHeadersTable.setSortable(false);
    responseHeadersTable.getTableHeader().setReorderingAllowed(false);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        responseHeadersTable.setHighlighters(highlighter);
    }

    responseHeadersPane.setViewportView(responseHeadersTable);
    responseHeadersDeleteButton.setEnabled(false);
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateLibrariesPanel.java

private void initComponents(Channel channel) {
    setBackground(UIConstants.BACKGROUND_COLOR);

    selectAllLabel = new JLabel("<html><u>Select All</u></html>");
    selectAllLabel.setForeground(Color.BLUE);
    selectAllLabel.addMouseListener(new MouseAdapter() {
        @Override/* www .  j av a  2  s  . c o m*/
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), true),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    selectSeparatorLabel = new JLabel("|");

    deselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    deselectAllLabel.setForeground(Color.BLUE);
    deselectAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), false),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    expandAllLabel = new JLabel("<html><u>Expand All</u></html>");
    expandAllLabel.setForeground(Color.BLUE);
    expandAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.expandAll();
        }
    });

    expandSeparatorLabel = new JLabel("|");

    collapseAllLabel = new JLabel("<html><u>Collapse All</u></html>");
    collapseAllLabel.setForeground(Color.BLUE);
    collapseAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.collapseAll();
        }
    });

    final TableCellEditor libraryCellEditor = new LibraryTreeCellEditor();

    libraryTreeTable = new MirthTreeTable() {
        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return libraryCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    DefaultTreeTableModel model = new SortableTreeTableModel();
    DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();
    model.setRoot(rootNode);

    libraryTreeTable.setLargeModel(true);
    libraryTreeTable.setTreeTableModel(model);
    libraryTreeTable.setOpenIcon(null);
    libraryTreeTable.setClosedIcon(null);
    libraryTreeTable.setLeafIcon(null);
    libraryTreeTable.setRootVisible(false);
    libraryTreeTable.setDoubleBuffered(true);
    libraryTreeTable.setDragEnabled(false);
    libraryTreeTable.setRowSelectionAllowed(true);
    libraryTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    libraryTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryTreeTable.setFocusable(true);
    libraryTreeTable.setOpaque(true);
    libraryTreeTable.setEditable(true);
    libraryTreeTable.setSortable(false);
    libraryTreeTable.setAutoCreateColumnsFromModel(false);
    libraryTreeTable.setShowGrid(true, true);
    libraryTreeTable.setTableHeader(null);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        libraryTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    libraryTreeTable.setTreeCellRenderer(new LibraryTreeCellRenderer());

    libraryTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            if (libraryTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                libraryTreeTable.clearSelection();
            }
        }
    });

    libraryTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                boolean visible = false;
                int selectedRow = libraryTreeTable.getSelectedRow();

                if (selectedRow >= 0) {
                    TreePath selectedPath = libraryTreeTable.getPathForRow(selectedRow);
                    if (selectedPath != null) {
                        visible = true;
                        Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) ((MutableTreeTableNode) selectedPath
                                .getLastPathComponent()).getUserObject();
                        String description = "";

                        if (selectedPath.getPathCount() == 2) {
                            description = libraryMap.get(triple.getLeft()).getDescription();
                        } else if (selectedPath.getPathCount() == 3) {
                            description = PlatformUI.MIRTH_FRAME.codeTemplatePanel.getCachedCodeTemplates()
                                    .get(triple.getLeft()).getDescription();
                        }

                        if (StringUtils.isBlank(description) || StringUtils.equals(description, CodeTemplateUtil
                                .getDocumentation(CodeTemplate.DEFAULT_CODE).getDescription())) {
                            descriptionTextPane.setText(
                                    "<html><body class=\"code-template-libraries-panel\"><i>No description.</i></body></html>");
                        } else {
                            descriptionTextPane.setText("<html><body class=\"code-template-libraries-panel\">"
                                    + MirthXmlUtil.encode(description) + "</body></html>");
                        }
                    }
                }

                descriptionScrollPane.setVisible(visible);
                updateUI();
            }
        }
    });

    libraryTreeTableScrollPane = new JScrollPane(libraryTreeTable);

    descriptionTextPane = new JTextPane();
    descriptionTextPane.setContentType("text/html");
    HTMLEditorKit editorKit = new HTMLEditorKit();
    StyleSheet styleSheet = editorKit.getStyleSheet();
    styleSheet.addRule(".code-template-libraries-panel {font-family:\"Tahoma\";font-size:11;text-align:top}");
    descriptionTextPane.setEditorKit(editorKit);
    descriptionTextPane.setEditable(false);
    descriptionScrollPane = new JScrollPane(descriptionTextPane);
    descriptionScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    descriptionScrollPane.setVisible(false);
}

From source file:eu.europeana.sip.gui.SipCreatorGUI.java

private JComponent createList() {
    dataSetList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    dataSetList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override/*from   w w  w  .ja v a  2  s. c o m*/
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting())
                return;
            int selected = dataSetList.getSelectedIndex();
            DataSetListModel.Entry selectedEntry = selected >= 0 ? dataSetListModel.getEntry(selected) : null;
            dataSetActions.setEntry(selectedEntry);
        }
    });
    dataSetList.setCellRenderer(new DataSetListModel.Cell());
    dataSetList.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    dataSetList.setBackground(getBackground());
    JScrollPane scroll = new JScrollPane(dataSetList);
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    return scroll;
}

From source file:edu.ku.brc.ui.ChooseFromListDlg.java

/**
 * Create the UI for the dialog.//from w ww .j ava2  s.c  o m
 * 
 * @param altName title for dialog
 * @param desc the list to be selected from
 * @param includeCancelBtn  indicates whether to create and display a cancel btn
 * @param includeHelpBtn indicates whether to create and display a help btn
 * @param helpContext help context identifier
 * @param titleArg title for dialog
 * @param desc the list to be selected from
 * @param includeCancelBtn indicates whether to create and display a cancel btn
 */
public void createUI() {
    setTitle(title);

    boolean hasDesc = StringUtils.isNotEmpty(desc);
    PanelBuilder builder = new PanelBuilder(
            new FormLayout("f:max(300px;p):g", "p," + (hasDesc ? "2px,p," : "") + "5px,p"));
    CellConstraints cc = new CellConstraints();
    //builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10));
    builder.setDefaultDialogBorder();

    int y = 1;
    if (hasDesc) {
        JLabel lbl = createLabel(desc, SwingConstants.CENTER);
        builder.add(lbl, cc.xy(1, y));
        y += 2;
    }

    try {
        ListModel listModel = new AbstractListModel() {
            public int getSize() {
                return items.size();
            }

            public Object getElementAt(int index) {
                return items.get(index).toString();
            }
        };

        list = new JList(listModel);
        if (icon != null) {
            list.setCellRenderer(getListCellRenderer()); // icon comes from the base
            // class (it's probably size
            // 16)
        }
        list.setSelectionMode(isMultiSelect ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
                : ListSelectionModel.SINGLE_SELECTION);
        list.setVisibleRowCount(10);

        if (selectedIndices != null) {
            list.setSelectedIndices(selectedIndices);
        }

        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    okBtn.doClick(); // emulate button click
                }
            }
        });
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    updateUIState();
                }
            }
        });
        JScrollPane listScroller = new JScrollPane(list);
        builder.add(listScroller, cc.xy(1, y));
        y += 2;

        // Bottom Button UI
        okBtn = createButton(StringUtils.isNotEmpty(okLabel) ? okLabel : getResourceString("OK"));
        okBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                isCancelled = false;
                btnPressed = OK_BTN;
                setVisible(false);
            }
        });
        getRootPane().setDefaultButton(okBtn);

        if ((whichBtns & CANCEL_BTN) == CANCEL_BTN) {
            cancelBtn = createButton(
                    StringUtils.isNotEmpty(cancelLabel) ? cancelLabel : getResourceString("CANCEL"));
            cancelBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    isCancelled = true;
                    btnPressed = CANCEL_BTN;
                    setVisible(false);
                }
            });
        }

        if ((whichBtns & HELP_BTN) == HELP_BTN) {
            helpBtn = createButton(
                    StringUtils.isNotEmpty(cancelLabel) ? cancelLabel : getResourceString("HELP"));
            if (StringUtils.isNotEmpty(helpContext)) {
                HelpMgr.registerComponent(helpBtn, helpContext);
            } else {
                helpBtn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        btnPressed = HELP_BTN;
                    }
                });
            }
        }

        if ((whichBtns & APPLY_BTN) == APPLY_BTN) {
            applyBtn = createButton(
                    StringUtils.isNotEmpty(applyLabel) ? applyLabel : getResourceString("Apply"));
            applyBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    btnPressed = APPLY_BTN;
                    if (isCloseOnApply) {
                        isCancelled = false;
                        setVisible(false);
                    }
                }
            });
        }

        JPanel bb;
        if (whichBtns == OK_BTN) {
            bb = ButtonBarFactory.buildOKBar(okBtn);

        } else if (whichBtns == OKCANCEL) {
            bb = ButtonBarFactory.buildOKCancelBar(okBtn, cancelBtn);

        } else if (whichBtns == OKCANCELAPPLY) {
            bb = ButtonBarFactory.buildOKCancelApplyBar(okBtn, cancelBtn, applyBtn);

        } else if (whichBtns == OKHELP) {
            bb = ButtonBarFactory.buildOKHelpBar(okBtn, helpBtn);

        } else if (whichBtns == OKCANCELHELP) {
            bb = ButtonBarFactory.buildOKCancelHelpBar(okBtn, cancelBtn, helpBtn);

        } else if (whichBtns == OKCANCELAPPLYHELP) {
            bb = ButtonBarFactory.buildOKCancelApplyHelpBar(okBtn, cancelBtn, applyBtn, helpBtn);

        } else {
            bb = ButtonBarFactory.buildOKBar(okBtn);
        }

        builder.add(bb, cc.xy(1, y));
        y += 2;

        updateUIState();

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ChooseFromListDlg.class, ex);
        log.error(ex);
    }

    setContentPane(builder.getPanel());
    pack();
    // setLocationRelativeTo(locationComp);
}

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

/**
 *
 *///  w  w  w  .j  a  va2 s  .c  o  m
protected void createUI() {
    kmlGen = new CollectingEventLocalityKMLGenerator();
    this.collectingEvents = new ArrayList<CollectingEvent>();

    CollectingEvent startCE = null;
    CollectingEvent endCE = null;

    Vector<Locality> localities = new Vector<Locality>();
    Vector<String> labels = new Vector<String>();
    for (Object obj : colEvents) {
        CollectingEvent collectingEvent = (CollectingEvent) obj;

        Locality locality = collectingEvent.getLocality();
        if (locality == null || locality.getLatitude1() == null || locality.getLongitude1() == null) {
            continue;
        }

        collectingEvents.add(collectingEvent);
        kmlGen.addDataObj(collectingEvent, "");

        if (collectingEvents.size() == 1) {
            startCE = collectingEvent;
            endCE = collectingEvent;
        }
        // XXX TODO FIX ME!
        if (startCE == null || endCE == null) {
            return;
        }
        // There may be an End Date that is further out than than the End Date of the last item
        // with the latest Start Date
        if (startCE.getStartDate().compareTo(collectingEvent.getStartDate()) > 1) {
            startCE = collectingEvent;
        }
        Calendar leftCal = endCE.getEndDate() != null ? endCE.getEndDate() : endCE.getStartDate();
        Calendar rightCal = collectingEvent.getEndDate() != null ? collectingEvent.getEndDate()
                : collectingEvent.getStartDate();
        if (leftCal.compareTo(rightCal) < 0) {
            endCE = collectingEvent;
        }

        Hashtable<String, Object> map = new Hashtable<String, Object>();

        Set<CollectionObject> colObjs = collectingEvent.getCollectionObjects();

        map.put("startDate", collectingEvent.getStartDate());
        map.put("endDate", collectingEvent.getEndDate());

        Set<Object> taxonNames = new HashSet<Object>();
        for (CollectionObject co : colObjs) {
            for (Determination d : co.getDeterminations()) {
                if (d.isCurrentDet()) {
                    //System.out.println(d.getTaxon().getName() + "("+co.getCountAmt()+")");
                    Taxon taxon = d.getPreferredTaxon();
                    if (taxon != null) {
                        taxonNames.add(taxon.getName()
                                + (co.getCountAmt() != null ? " (" + co.getCountAmt() + ")" : ""));
                        if (taxon.getRankId() == 220) {
                            Taxon genus = taxon.getParent();
                            if (genus.getRankId() == 180) {
                                ImageGetter imgGetter = new ImageGetter(imageGetterList, imageMap, imageURLs,
                                        genus.getName(), taxon.getName());
                                imageGetterList.add(imgGetter);
                            }
                        }
                    }
                    break;
                }
            }
        }
        map.put("taxonItems", taxonNames);

        map.put("latitude1", locality.getLatitude1());
        map.put("longitude1", locality.getLongitude1());

        /*
        Calendar cal = collectingEvent.getStartDate();
        if (cal != null)
        {
          labels.add(scrDateFormat.format(cal.getTime()));
                
        } else if (collectingEvent.getVerbatimDate() != null)
        {
          labels.add(collectingEvent.getVerbatimDate());
                
        } else
        {
          labels.add(Integer.toString(collectingEvent.getCollectingEventId()));
                
        }
        */
        labels.add(Integer.toString(collectingEvents.size()));
        localities.add(locality);
        valueList.add(map);

    }

    // XXX Fix me shouldn't be hard coded here to make it work
    localityMapper.setMaxMapWidth(515);
    localityMapper.setMaxMapHeight(375);

    Color arrow = new Color(220, 220, 220);
    localityMapper.setArrowColor(arrow);
    localityMapper.setDotColor(Color.WHITE);
    localityMapper.setDotSize(4);
    localityMapper.setLabelColor(Color.RED);

    int inx = 0;
    for (Locality locality : localities) {
        localityMapper.addLocationAndLabel(locality, labels != null ? labels.get(inx) : null);
        inx++;
    }
    localityMapper.setCurrentLoc(localities.get(0));
    localityMapper.setCurrentLocColor(Color.RED);

    // XXX DEMO  (Hard Coded 'null' means everyone would have one which may not be true)
    // "null" ViewSet name means it should use the default
    ViewIFace view = AppContextMgr.getInstance().getView("LocalityMapper");

    // TODO WHERE's the ERROR checking !
    multiView = new MultiView(null, null, view, AltViewIFace.CreationMode.VIEW, MultiView.NO_OPTIONS);
    multiView.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(138, 128, 128)),
                    BorderFactory.createEmptyBorder(4, 4, 4, 4)));

    formViewObj = multiView.getCurrentViewAsFormViewObj();
    formViewObj.getUIComponent().setBackground(Color.WHITE);

    imageJList = formViewObj.getCompById("taxonItems");
    imageJList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                String nameStr = (String) imageJList.getSelectedValue();
                if (nameStr != null) {
                    int index = nameStr.indexOf(" (");
                    if (index > -1) {
                        nameStr = nameStr.substring(0, index);
                    }
                }

                //System.out.println("Getting["+name+"]");
                Image img = null;
                if (StringUtils.isNotEmpty(nameStr)) {
                    img = imageMap.get(nameStr); // might return null
                    ImageDisplay imgDisplay = formViewObj.getCompById("image");
                    if (img != null) {
                        imgDisplay.setImage(new ImageIcon(img));
                    } else {
                        imgDisplay.setImage((Image) null);
                    }
                }

            }
        }
    });

    // XXX TODO FIX ME!
    if (startCE == null || endCE == null) {
        return;
    }
    String startDateStr = scrDateFormat.format(startCE.getStartDate().getTime());
    String endDateStr = scrDateFormat
            .format((endCE.getEndDate() != null ? endCE.getEndDate() : endCE.getStartDate()).getTime());

    Formatter formatter = new Formatter();
    titleLabel.setText(formatter
            .format(getResourceString("LocalityMapperTitle"), new Object[] { startDateStr, endDateStr })
            .toString());

    Font font = titleLabel.getFont();
    titleLabel.setFont(new Font(font.getFontName(), Font.BOLD, font.getSize() + 2));

    recordSetController = new ResultSetController(null, false, false, false, null, collectingEvents.size(),
            true);
    recordSetController.addListener(this);
    recordSetController.getPanel().setBackground(Color.WHITE);

    controlPanel = new ControlBarPanel(getBackground());
    controlPanel.add(recordSetController.getPanel());
    controlPanel.setRecordSetController(recordSetController);
    controlPanel.setBackground(Color.WHITE);

    googleBtn = new JButton(IconManager.getIcon("GoogleEarth", IconManager.STD_ICON_SIZE));
    googleBtn.setMargin(new Insets(1, 1, 1, 1));
    googleBtn.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
    googleBtn.setSize(new Dimension(18, 18));
    googleBtn.setPreferredSize(new Dimension(18, 18));
    googleBtn.setMaximumSize(new Dimension(18, 18));
    googleBtn.setFocusable(false);
    googleBtn.setBackground(Color.WHITE);

    controlPanel.addButtons(new JButton[] { googleBtn }, false);

    googleBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            try {
                UIRegistry.displayStatusBarText("Exporting Collecting Events in KML."); // XXX I18N
                kmlGen.setSpeciesToImageMapper(imageURLs);
                kmlGen.outputToFile(System.getProperty("user.home") + File.separator + "specify.kml");

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalityMapperSubPane.class, ex);
                ex.printStackTrace();
            }
        }
    });

    addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
            // nothing
        }

        public void mouseMoved(MouseEvent e) {
            checkMouseLocation(e.getPoint(), false);
        }
    });

    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            checkMouseLocation(e.getPoint(), true);
        }

    });

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            getLocalityMap();
        }
    });

}

From source file:edu.ku.brc.specify.ui.treetables.TreeDefinitionEditor.java

/**
 * Adds a selection listener.//from  w  ww  .  j  a  v  a  2 s.  c o m
 */
protected void addSelectionListener() {
    ListSelectionListener sl = new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            clearStatus();
            selectionValueChanged();
        }
    };
    defItemsTable.getSelectionModel().addListSelectionListener(sl);
}

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

/**
 * Constructor of a results "table" which is really a panel
 * @param esrPane the parent//from   ww  w.  j  a  va 2 s  . com
 * @param erTableInfo the info describing the results
 * @param installServices indicates whether services should be installed
 * @param isExpandedAtStartUp enough said
 * @param inclCloseBtn whether to include the close button on the bar
 */
public ESResultsTablePanel(final ExpressSearchResultsPaneIFace esrPane, final QueryForIdResultsIFace results,
        final boolean installServices, final boolean isExpandedAtStartUp, final boolean inclCloseBtn) {
    super(new BorderLayout());

    this.esrPane = esrPane;
    this.results = results;
    this.bannerColor = results.getBannerColor();
    this.isEditable = results.isEditingEnabled();

    table = new JTable();
    table.setShowVerticalLines(false);
    table.setRowSelectionAllowed(true);
    table.setSelectionMode(results.isMultipleSelection() ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
            : ListSelectionModel.SINGLE_SELECTION);

    setBackground(table.getBackground());

    if (isEditable) {
        addContextMenu();
    }

    topTitleBar = new GradiantLabel(results.getTitle(), SwingConstants.LEFT);
    topTitleBar.setBGBaseColor(bannerColor);
    topTitleBar.setTextColor(Color.WHITE);
    topTitleBar.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getClickCount() == 2) {
                expandBtn.doClick();
            }
        }
    });

    String description = results.getDescription();
    if (StringUtils.isNotEmpty(description)) {
        topTitleBar.setToolTipText(description);
    }

    expandBtn = new TriangleButton();
    expandBtn.setToolTipText(getResourceString("CollapseTBL"));
    expandBtn.setForeground(bannerColor);
    expandBtn.setTextColor(Color.WHITE);

    showTopNumEntriesBtn = new GradiantButton(
            String.format(getResourceString("ShowTopEntries"), new Object[] { topNumEntries }));
    showTopNumEntriesBtn.setForeground(bannerColor);
    showTopNumEntriesBtn.setTextColor(Color.WHITE);
    showTopNumEntriesBtn.setVisible(false);
    showTopNumEntriesBtn.setCursor(handCursor);

    List<ServiceInfo> services = installServices ? getServices() : null;

    //System.out.println("["+tableInfo.getTableId()+"]["+services.size()+"]");
    StringBuffer colDef = new StringBuffer("p,0px,p:g,0px,p,0px,");
    int numCols = (installServices ? services.size() : 0) + (inclCloseBtn ? 1 : 0);
    colDef.append(UIHelper.createDuplicateJGoodiesDef("p", "0px", numCols)); // add additional col defs for services

    PanelBuilder builder = new PanelBuilder(new FormLayout(colDef.toString(), "f:p:g"));
    CellConstraints cc = new CellConstraints();

    int col = 1;
    builder.add(expandBtn, cc.xy(col, 1));
    col += 2;

    builder.add(topTitleBar, cc.xy(col, 1));
    col += 2;

    builder.add(showTopNumEntriesBtn, cc.xy(col, 1));
    col += 2;

    if (installServices && services.size() > 0) {
        serviceBtns = new Hashtable<ServiceInfo, JButton>();

        //IconManager.IconSize size = IconManager.
        int iconSize = AppPreferences.getLocalPrefs().getInt("banner.icon.size", 20);
        // Install the buttons on the banner with available services
        for (ServiceInfo serviceInfo : services) {
            GradiantButton btn = new GradiantButton(serviceInfo.getIcon(iconSize)); // XXX PREF
            btn.setToolTipText(serviceInfo.getTooltip());
            btn.setForeground(bannerColor);
            builder.add(btn, cc.xy(col, 1));
            ESTableAction esta = new ESTableAction(serviceInfo.getCommandAction(), table,
                    serviceInfo.getTooltip());
            esta.setProperty("gridtitle", results.getTitle());
            btn.addActionListener(esta);
            serviceBtns.put(serviceInfo, btn);
            col += 2;
        }
    }

    GradiantButton closeBtn = null;
    if (inclCloseBtn) {
        closeBtn = new GradiantButton(IconManager.getIcon("Close"));
        closeBtn.setToolTipText(getResourceString("ESCloseTable"));
        closeBtn.setForeground(bannerColor);
        closeBtn.setRolloverEnabled(true);
        closeBtn.setRolloverIcon(IconManager.getIcon("CloseHover"));
        closeBtn.setPressedIcon(IconManager.getIcon("CloseHover"));
        builder.add(closeBtn, cc.xy(col, 1));
        col += 2;
    }

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

    tablePane = new JPanel(new BorderLayout());
    setupTablePane();

    if (isEditable) {
        //delRSItems = UIHelper.createI18NButton("RESTBL_DEL_ITEMS");
        delRSItems = UIHelper.createIconBtn("DelRec", "ESDelRowsTT", null);
        delRSItems.addActionListener(createRemoveItemAL());
        delRSItems.setEnabled(false);

        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    delRSItems.setEnabled(table.getSelectedRowCount() > 0);
                }
            }
        });
    }

    add(tablePane, BorderLayout.CENTER);

    moveToRSCmd = new DragSelectedRowsBtn(IconManager.getIcon("Record_Set", IconManager.IconSize.Std16));

    if (installServices) {
        PanelBuilder bottomBar = new PanelBuilder(
                new FormLayout("4px,p,4px,p,4px,p," + (delRSItems != null ? "4px,p," : "") + "f:p:g", "p"));
        bottomBar.add(moveToRSCmd, cc.xy(2, 1));
        bottomBar.add(selectAllBtn, cc.xy(4, 1));
        bottomBar.add(deselectAllBtn, cc.xy(6, 1));
        if (delRSItems != null) {
            bottomBar.add(delRSItems, cc.xy(8, 1));
        }
        botBtnPanel = bottomBar.getPanel();

        deselectAllBtn.setEnabled(false);
        selectAllBtn.setEnabled(true);
        moveToRSCmd.setEnabled(true);

        deselectAllBtn.setToolTipText(getResourceString("SELALLTOOLTIP"));
        selectAllBtn.setToolTipText(getResourceString("DESELALLTOOLTIP"));
        moveToRSCmd.setToolTipText(getResourceString("MOVEROWSTOOLTIP"));

        selectAllBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                table.selectAll();
            }
        });

        deselectAllBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
            }
        });

        moveToRSCmd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RecordSetIFace src = (RecordSetIFace) moveToRSCmd.getData();
                CommandDispatcher
                        .dispatch(new CommandAction(RecordSetTask.RECORD_SET, "AskForNewRS", src, null, null));
            }
        });

        add(botBtnPanel, BorderLayout.SOUTH);

    } else {
        botBtnPanel = null;
    }

    expandBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            expandTable(false);
        }
    });

    if (!isExpandedAtStartUp) {
        expandTable(true);
    }

    showTopNumEntriesBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            morePanel.setVisible(true);
            showTopNumEntriesBtn.setVisible(false);
            showingAllRows = false;
            setDisplayRows(rowCount, topNumEntries);

            // If it is collapsed then expand it
            if (!expandBtn.isDown()) {
                tablePane.setVisible(true);
                expandBtn.setDown(true);
            }

            // Make sure the layout is updated
            invalidate();
            doLayout();
            esrPane.revalidateScroll();
        }
    });

    if (closeBtn != null) {
        closeBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        removeMe();
                    }
                });

            }
        });
    }

    ResultSetTableModel rsm = createModel();
    rsm.setPropertyListener(this);
    resultSetTableModel = rsm;
    table.setRowSorter(new TableRowSorter<ResultSetTableModel>(resultSetTableModel));

    table.setRowSelectionAllowed(true);
    table.setModel(rsm);

    configColumns();

    rowCount = rsm.getRowCount();
    if (rowCount > topNumEntries + 2) {
        buildMorePanel();
        setDisplayRows(rowCount, topNumEntries);
    } else {
        setDisplayRows(rowCount, Integer.MAX_VALUE);
    }

    invalidate();
    doLayout();
    UIRegistry.forceTopFrameRepaint();

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (botBtnPanel != null) {
                    deselectAllBtn.setEnabled(table.getSelectedRowCount() > 0);
                    selectAllBtn.setEnabled(table.getSelectedRowCount() != table.getRowCount());
                    moveToRSCmd.setEnabled(table.getSelectedRowCount() > 0);
                }
            }
            if (propChangeListener != null) {
                if (!e.getValueIsAdjusting()) {
                    propChangeListener.propertyChange(
                            new PropertyChangeEvent(this, "selection", table.getSelectedRowCount(), 0));

                } else {
                    propChangeListener.propertyChange(
                            new PropertyChangeEvent(this, "selection", table.getSelectedRowCount(), 0));
                }
            }
        }
    });

    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //synchronized (((JTable)e.getSource()).getTreeLock()) 
            //{
            doDoubleClickOnRow(e);
            //}
        }
    });

    // Horizontal Alignment is set later
    TableColumnModel tableColModel = table.getColumnModel();
    for (int i = 0; i < tableColModel.getColumnCount(); i++) {
        tableColModel.getColumn(i).setCellRenderer(new BiColorTableCellRenderer());
    }
}

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

@Override
public void createUI() {
    super.createUI();

    databaseSchema = WorkbenchTask.getDatabaseSchema();

    int disciplineeId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
    SchemaI18NService.getInstance().loadWithLocale(SpLocaleContainer.WORKBENCH_SCHEMA, disciplineeId,
            databaseSchema, SchemaI18NService.getCurrentLocale());

    // Create the Table List
    Vector<TableInfo> tableInfoList = new Vector<TableInfo>();
    for (DBTableInfo ti : databaseSchema.getTables()) {
        if (StringUtils.isNotEmpty(ti.toString())) {
            TableInfo tableInfo = new TableInfo(ti, IconManager.STD_ICON_SIZE);
            tableInfoList.add(tableInfo);

            Vector<FieldInfo> fldList = new Vector<FieldInfo>();
            for (DBFieldInfo fi : ti.getFields()) {
                String fldTitle = fi.getTitle().replace(" ", "");
                if (fldTitle.equalsIgnoreCase(fi.getName())) {
                    //get title from mapped field
                    UploadInfo upInfo = getUploadInfo(fi);
                    DBFieldInfo mInfo = getMappedFieldInfo(fi);
                    if (mInfo != null) {
                        String title = mInfo.getTitle();
                        if (upInfo != null && upInfo.getSequence() != -1) {
                            title += " " + (upInfo.getSequence() + 1);
                        }//from  w w w . j  a  v a 2 s . c o  m
                        //if mapped-to table is different than the container table used
                        // in the wb, add the mapped-to table's title
                        if (mInfo.getTableInfo().getTableId() != ti.getTableId()) {
                            title = mInfo.getTableInfo().getTitle() + " " + title;
                        }
                        fi.setTitle(title);
                    }
                }
                fldList.add(new FieldInfo(ti, fi));
            }
            //Collections.sort(fldList);
            tableInfo.setFieldItems(fldList);
        }
    }
    Collections.sort(tableInfoList);

    fieldModel = new DefaultModifiableListModel<FieldInfo>();
    tableModel = new DefaultModifiableListModel<TableInfo>();
    for (TableInfo ti : tableInfoList) {
        tableModel.add(ti);

        // only added for layout
        for (FieldInfo fi : ti.getFieldItems()) {
            fieldModel.add(fi);
        }
    }

    tableList = new JList(tableModel);
    tableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    tableList.setCellRenderer(tableInfoListRenderer = new TableInfoListRenderer(IconManager.STD_ICON_SIZE));
    JScrollPane tableScrollPane = new JScrollPane(tableList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    tableList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                Object selObj = tableList.getSelectedValue();
                if (selObj != null) {
                    fillFieldList((TableInfo) selObj);
                }
                updateEnabledState();
            }
        }
    });

    fieldList = new JList(fieldModel);
    fieldList.setCellRenderer(tableInfoListRenderer = new TableInfoListRenderer(IconManager.STD_ICON_SIZE));
    fieldList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    JScrollPane fieldScrollPane = new JScrollPane(fieldList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    fieldList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateEnabledState();
                updateFieldDescription();
            }
        }
    });

    mapModel = new DefaultModifiableListModel<FieldMappingPanel>();
    mapList = new JList(mapModel);
    mapList.setCellRenderer(new MapCellRenderer());
    mapList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    mapScrollPane = new JScrollPane(mapList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    mapList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                FieldMappingPanel fmp = (FieldMappingPanel) mapList.getSelectedValue();
                if (fmp != null) {
                    ignoreMapListUpdate = true;

                    FieldInfo fldInfo = fmp.getFieldInfo();
                    if (fldInfo != null) {
                        for (int i = 0; i < tableModel.size(); i++) {
                            TableInfo tblInfo = (TableInfo) tableModel.get(i);
                            if (fldInfo.getTableinfo() == tblInfo.getTableInfo()) {
                                tableList.setSelectedValue(tblInfo, true);
                                fillFieldList(tblInfo);
                                //System.out.println(fldInfo.hashCode()+" "+fldInfo.getFieldInfo().hashCode());
                                fieldList.setSelectedValue(fldInfo, true);
                                updateFieldDescription();
                                break;
                            }
                        }
                    }
                    ignoreMapListUpdate = false;
                    updateEnabledState();
                }
            }
        }
    });

    upBtn = createIconBtn("ReorderUp", "WB_MOVE_UP", new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            int inx = mapList.getSelectedIndex();
            FieldMappingPanel fmp = mapModel.getElementAt(inx);

            mapModel.remove(fmp);
            mapModel.insertElementAt(fmp, inx - 1);
            mapList.setSelectedIndex(inx - 1);
            updateEnabledState();
            setChanged(true);
        }
    });
    downBtn = createIconBtn("ReorderDown", "WB_MOVE_DOWN", new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            int inx = mapList.getSelectedIndex();
            FieldMappingPanel fmp = mapModel.getElementAt(inx);

            mapModel.remove(fmp);
            mapModel.insertElementAt(fmp, inx + 1);
            mapList.setSelectedIndex(inx + 1);
            updateEnabledState();
            setChanged(true);
        }
    });

    JButton dumpMappingBtn = createIconBtn("BlankIcon", IconManager.IconSize.Std16, "WB_MAPPING_DUMP",
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    dumpMapping();
                }
            });
    dumpMappingBtn.setEnabled(true);
    dumpMappingBtn.setFocusable(false);
    dumpMappingBtn.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            ((JButton) e.getSource()).setIcon(IconManager.getIcon("Save", IconManager.IconSize.Std16));
            super.mouseEntered(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            ((JButton) e.getSource()).setIcon(IconManager.getIcon("BlankIcon", IconManager.IconSize.Std16));
            super.mouseExited(e);
        }

    });

    mapToBtn = createIconBtn("Map", "WB_ADD_MAPPING_ITEM", new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            map();
        }
    });
    unmapBtn = createIconBtn("Unmap", "WB_REMOVE_MAPPING_ITEM", new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            unmap();
        }
    });

    // Adjust all Labels depending on whether we are creating a new template or not
    // and whether it is from a file or not
    String mapListLeftLabel;
    String mapListRightLabel;

    // Note: if workbenchTemplate is null then it is 
    String dataTypeLabel = getResourceString("WB_DATA_TYPE");
    String fieldsLabel = getResourceString("WB_FIELDS");

    mapListLeftLabel = fieldsLabel;
    mapListRightLabel = getResourceString("WB_COLUMNS");

    CellConstraints cc = new CellConstraints();

    JPanel mainLayoutPanel = new JPanel();

    PanelBuilder labelsBldr = new PanelBuilder(new FormLayout("p, f:p:g, p", "p"));
    labelsBldr.add(createLabel(mapListLeftLabel, SwingConstants.LEFT), cc.xy(1, 1));
    labelsBldr.add(createLabel(mapListRightLabel, SwingConstants.RIGHT), cc.xy(3, 1));

    PanelBuilder upDownPanel = new PanelBuilder(new FormLayout("p", "p,f:p:g, p, 2px, p, f:p:g"));
    upDownPanel.add(dumpMappingBtn, cc.xy(1, 1));
    upDownPanel.add(upBtn, cc.xy(1, 3));
    upDownPanel.add(downBtn, cc.xy(1, 5));

    PanelBuilder middlePanel = new PanelBuilder(new FormLayout("c:p:g", "p, 2px, p"));
    middlePanel.add(mapToBtn, cc.xy(1, 1));
    middlePanel.add(unmapBtn, cc.xy(1, 3));

    btnPanel = middlePanel.getPanel();
    btnPanel.setOpaque(false);

    PanelBuilder outerMiddlePanel = new PanelBuilder(new FormLayout("c:p:g", "f:p:g, p, f:p:g"));
    outerMiddlePanel.add(btnPanel, cc.xy(1, 2));
    outerMiddlePanel.getPanel().setOpaque(false);

    // Main Pane Layout
    PanelBuilder builder = new PanelBuilder(
            new FormLayout("f:max(200px;p):g, 5px, max(200px;p), 5px, p:g, 5px, f:max(250px;p):g, 2px, p",
                    "p, 2px, f:max(350px;p):g"),
            mainLayoutPanel);

    builder.add(createLabel(dataTypeLabel, SwingConstants.CENTER), cc.xy(1, 1));
    builder.add(createLabel(fieldsLabel, SwingConstants.CENTER), cc.xy(3, 1));
    builder.add(labelsBldr.getPanel(), cc.xy(7, 1));

    builder.add(tableScrollPane, cc.xy(1, 3));
    builder.add(fieldScrollPane, cc.xy(3, 3));

    builder.add(outerMiddlePanel.getPanel(), cc.xy(5, 3));

    builder.add(mapScrollPane, cc.xy(7, 3));
    builder.add(upDownPanel.getPanel(), cc.xy(9, 3));

    mainLayoutPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    JPanel megaPanel = new JPanel(new BorderLayout());
    megaPanel.add(mainLayoutPanel, BorderLayout.CENTER);
    descriptionLbl = createLabel("  ", SwingConstants.LEFT);
    //PanelBuilder descBuilder = new PanelBuilder(new FormLayout("f:p:g, 3dlu","p"));
    //descBuilder.add(descriptionLbl, cc.xy(1, 1));
    //megaPanel.add(descBuilder.getPanel(), BorderLayout.SOUTH);
    megaPanel.add(descriptionLbl, BorderLayout.SOUTH);
    //contentPanel = mainLayoutPanel;
    contentPanel = megaPanel;

    Color bgColor = btnPanel.getBackground();
    int inc = 16;
    btnPanelColor = new Color(Math.min(255, bgColor.getRed() + inc), Math.min(255, bgColor.getGreen() + inc),
            Math.min(255, bgColor.getBlue() + inc));
    btnPanel.setBackground(btnPanelColor);
    btnPanel.setBorder(BorderFactory.createEmptyBorder(4, 6, 4, 6));

    okBtn.setEnabled(false);

    HelpMgr.registerComponent(helpBtn, helpContext);

    if (dataFileInfo != null) {
        autoMapFromDataFile(dataFileInfo.getColInfo());
    }
    if (workbenchTemplate != null) {
        fillFromTemplate();
        setChanged(false);
    }

    mainPanel.add(contentPanel, BorderLayout.CENTER);

    if (dataFileInfo == null) //can't add new mappings when importing.
    {
        FieldMappingPanel fmp = addMappingItem(null,
                IconManager.getIcon("BlankIcon", IconManager.STD_ICON_SIZE), null);
        fmp.setAdded(true);
        fmp.setNew(true);
    }

    pack();

    SwingUtilities.invokeLater(new Runnable() {
        @SuppressWarnings("synthetic-access")
        public void run() {
            cancelBtn.requestFocus();
            fieldModel.clear();
            fieldList.clearSelection();
            updateFieldDescription();
            updateEnabledState();

            if (mapModel.size() > 1) {
                mapList.clearSelection();
            }
        }
    });
}

From source file:com.diversityarrays.kdxplore.field.FieldViewDialog.java

public FieldViewDialog(Window owner, String title, SampleGroupChoice sgcSamples, Trial trial,
        SampleGroupChoice sgcNewMedia, KDSmartDatabase db) throws IOException {
    super(owner, title, ModalityType.MODELESS);

    advanceRetreatControls = Box.createHorizontalBox();
    advanceRetreatControls.add(new JButton(retreatAction));
    advanceRetreatControls.add(new JButton(advanceAction));

    autoAdvanceControls = Box.createHorizontalBox();
    autoAdvanceControls.add(new JButton(autoAdvanceAction));

    autoAdvanceOption.addActionListener(new ActionListener() {
        @Override// www  .j ava 2s  .  co m
        public void actionPerformed(ActionEvent e) {
            updateMovementControls();
        }
    });

    this.database = db;
    this.sampleGroupChoiceForSamples = sgcSamples;
    this.sampleGroupChoiceForNewMedia = sgcNewMedia;

    NumberSpinner fontSpinner = new NumberSpinner(new SpinnerNumberModel(), "0.00");

    this.fieldViewPanel = FieldViewPanel.create(database, trial, SeparatorVisibilityOption.VISIBLE, null,
            Box.createHorizontalGlue(), new JButton(showInfoAction), Box.createHorizontalGlue(),
            new JLabel("Font Size:"), fontSpinner, Box.createHorizontalGlue(), advanceRetreatControls,
            autoAdvanceOption, autoAdvanceControls);

    initialiseAction(advanceAction, "ic_object_advance_black.png", "Auto-Advance");

    this.xyProvider = fieldViewPanel.getXYprovider();
    this.traitMap = fieldViewPanel.getTraitMap();

    fieldLayoutTable = fieldViewPanel.getFieldLayoutTable();

    JScrollPane scrollPane = fieldViewPanel.getFieldTableScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    fieldLayoutTable.setTransferHandler(flth);
    fieldLayoutTable.setDropMode(DropMode.ON);

    fieldLayoutTable.addMouseListener(new MouseAdapter() {
        JPopupMenu popupMenu;

        @Override
        public void mouseClicked(MouseEvent e) {
            if (!SwingUtilities.isRightMouseButton(e) || 1 != e.getClickCount()) {
                return;
            }
            Point pt = e.getPoint();
            int row = fieldLayoutTable.rowAtPoint(pt);
            if (row >= 0) {
                int col = fieldLayoutTable.columnAtPoint(pt);
                if (col >= 0) {
                    Plot plot = fieldViewPanel.getPlotAt(col, row);
                    if (plot != null) {
                        if (popupMenu == null) {
                            popupMenu = new JPopupMenu("View Attachments");
                        }
                        popupMenu.removeAll();

                        Set<File> set = plot.getMediaFiles();
                        if (Check.isEmpty(set)) {
                            popupMenu.add(new JMenuItem("No Attachments available"));
                        } else {
                            for (File file : set) {
                                Action a = new AbstractAction(file.getName()) {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        try {
                                            Desktop.getDesktop().browse(file.toURI());
                                        } catch (IOException e1) {
                                            MsgBox.warn(FieldViewDialog.this, e1, file.getName());
                                        }
                                    }
                                };
                                popupMenu.add(new JMenuItem(a));
                            }
                        }
                        popupMenu.show(fieldLayoutTable, pt.x, pt.y);
                    }
                }
            }
        }

    });
    Font font = fieldLayoutTable.getFont();
    float fontSize = font.getSize2D();

    fontSizeModel = new SpinnerNumberModel(fontSize, fontSize, 50.0, 1.0);
    fontSpinner.setModel(fontSizeModel);
    fontSizeModel.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            float fsize = fontSizeModel.getNumber().floatValue();
            System.out.println("Using fontSize=" + fsize);
            Font font = fieldLayoutTable.getFont().deriveFont(fsize);
            fieldLayoutTable.setFont(font);
            FontMetrics fm = fieldLayoutTable.getFontMetrics(font);
            int lineHeight = fm.getMaxAscent() + fm.getMaxDescent();
            fieldLayoutTable.setRowHeight(4 * lineHeight);

            //                GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false);

            fieldLayoutTable.repaint();
        }
    });

    fieldLayoutTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fieldLayoutTable.setResizable(true, true);
    fieldLayoutTable.getTableColumnResizer().setResizeAllColumns(true);

    advanceAction.setEnabled(false);
    fieldLayoutTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }
    });
    TableColumnModel columnModel = fieldLayoutTable.getColumnModel();
    columnModel.addColumnModelListener(new TableColumnModelListener() {
        @Override
        public void columnSelectionChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

        @Override
        public void columnAdded(TableColumnModelEvent e) {
        }
    });

    PropertyChangeListener listener = new PropertyChangeListener() {
        // Use a timer and redisplay other columns when delay is GT 100 ms

        Timer timer = new Timer(true);
        TimerTask timerTask;
        long lastActive;
        boolean busy = false;
        private int eventColumnWidth;
        private TableColumn eventColumn;

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (busy) {
                return;
            }

            if (evt.getSource() instanceof TableColumn && "width".equals(evt.getPropertyName())) {

                eventColumn = (TableColumn) evt.getSource();
                eventColumnWidth = eventColumn.getWidth();

                lastActive = System.currentTimeMillis();
                if (timerTask == null) {
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if (System.currentTimeMillis() - lastActive > 200) {
                                timerTask.cancel();
                                timerTask = null;

                                busy = true;
                                try {
                                    for (Enumeration<TableColumn> en = columnModel.getColumns(); en
                                            .hasMoreElements();) {
                                        TableColumn tc = en.nextElement();
                                        if (tc != eventColumn) {
                                            tc.setWidth(eventColumnWidth);
                                        }
                                    }
                                } finally {
                                    busy = false;
                                }
                            }
                        }
                    };
                    timer.scheduleAtFixedRate(timerTask, 100, 150);
                }
            }
        }
    };
    for (Enumeration<TableColumn> en = columnModel.getColumns(); en.hasMoreElements();) {
        TableColumn tc = en.nextElement();
        tc.addPropertyChangeListener(listener);
    }

    Map<Integer, Plot> plotById = new HashMap<>();
    for (Plot plot : fieldViewPanel.getFieldLayout()) {
        plotById.put(plot.getPlotId(), plot);
    }

    TrialItemVisitor<Sample> sampleVisitor = new TrialItemVisitor<Sample>() {
        @Override
        public void setExpectedItemCount(int count) {
        }

        @Override
        public boolean consumeItem(Sample sample) throws IOException {

            Plot plot = plotById.get(sample.getPlotId());
            if (plot == null) {
                throw new IOException("Missing plot for plotId=" + sample.getPlotId() + " sampleIdent="
                        + Util.createUniqueSampleKey(sample));
            }
            plot.addSample(sample);

            SampleCounts counts = countsByTraitId.get(sample.getTraitId());
            if (counts == null) {
                counts = new SampleCounts();
                countsByTraitId.put(sample.getTraitId(), counts);
            }
            if (sample.hasBeenScored()) {
                ++counts.scored;
            } else {
                ++counts.unscored;
            }
            return true;
        }
    };
    database.visitSamplesForTrial(sampleGroupChoiceForSamples, trial.getTrialId(),
            SampleOrder.ALL_BY_PLOT_ID_THEN_TRAIT_ID_THEN_INSTANCE_NUMBER_ORDER_THEN_SPECIMEN_NUMBER,
            sampleVisitor);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.trial = trial;

    KDClientUtils.initAction(ImageId.SETTINGS_24, showInfoAction, "Trial Summary");

    Action clear = new AbstractAction("Clear") {
        @Override
        public void actionPerformed(ActionEvent e) {
            infoTextArea.setText("");
        }
    };
    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(GuiUtil.createLabelSeparator("Plot Details", new JButton(clear)), BorderLayout.NORTH);
    bottom.add(new JScrollPane(infoTextArea), BorderLayout.CENTER);
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, fieldViewPanel,
            new JScrollPane(infoTextArea));
    splitPane.setResizeWeight(0.0);
    splitPane.setOneTouchExpandable(true);

    setContentPane(splitPane);

    updateMovementControls();
    pack();
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFarmManager.java

/**
 * Creates new form DSWorkbenchFarmManager
 *//*from   w  w  w  .  j a  v a2s.  c om*/
DSWorkbenchFarmManager() {
    initComponents();
    centerPanel = new GenericTestPanel();
    jCenterPanel.add(centerPanel, BorderLayout.CENTER);
    centerPanel.setChildComponent(jFarmPanel);
    buildMenu();
    jFarmTable.setModel(new FarmTableModel());
    jFarmTable.getTableHeader().setDefaultRenderer(new de.tor.tribes.ui.renderer.DefaultTableHeaderRenderer());
    ColorHighlighter p = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.BARBARIAN));
    p.setBackground(Color.LIGHT_GRAY);
    ColorHighlighter p1 = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.PLAYER));
    p1.setBackground(new Color(0xffffcc));
    jFarmTable.setHighlighters(
            HighlighterFactory.createAlternateStriping(Constants.DS_ROW_A, Constants.DS_ROW_B), p, p1);
    jFarmTable.setDefaultRenderer(Boolean.class,
            new CustomBooleanRenderer(CustomBooleanRenderer.LayoutStyle.RES_IN_STORAGE));
    jFarmTable.setDefaultRenderer(Date.class, new de.tor.tribes.ui.renderer.DateCellRenderer());
    jFarmTable.setDefaultRenderer(Float.class, new de.tor.tribes.ui.renderer.PercentCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmStatus));
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_RESULT.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmResult));
    jFarmTable.setDefaultRenderer(StorageStatus.class, new de.tor.tribes.ui.renderer.StorageCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.SIEGE_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.SiegeStatus));
    jFarmTable.setColumnControlVisible(true);
    jFarmTable.setSortsOnUpdates(false);
    FarmManager.getSingleton().addManagerListener(DSWorkbenchFarmManager.this);
    settingsPanel.setLayout(new BorderLayout());
    settingsPanel.add(jSettingsPanel, BorderLayout.CENTER);

    new Timer("FarmTableUpdate").schedule(new TimerTask() {

        @Override
        public void run() {
            jFarmTable.repaint();
        }
    }, new Date(), 1000);

    KeyStroke delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false);
    KeyStroke farmA = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false);
    KeyStroke farmB = KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, false);
    KeyStroke farmK = KeyStroke.getKeyStroke(KeyEvent.VK_K, 0, false);
    KeyStroke farmC = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0, false);
    ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            deleteSelection();
        }
    };

    capabilityInfoPanel1.addActionListener(listener);

    jFarmTable.setSortsOnUpdates(false);
    jFarmTable.registerKeyboardAction(listener, "Delete", delete,
            JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmA();
        }
    }, "FarmA", farmA, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmB();
        }
    }, "FarmB", farmB, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmK();
        }
    }, "FarmK", farmK, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmC();
        }
    }, "FarmC", farmC, JComponent.WHEN_IN_FOCUSED_WINDOW);

    aTroops = new TroopSelectionPanelDynamic();
    aTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    bTroops = new TroopSelectionPanelDynamic();
    bTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    kTroops = new TroopSelectionPanelDynamic();
    kTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    cTroops = new TroopSelectionPanelDynamic();
    cTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    rTroops = new TroopSelectionPanelDynamic();
    rTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    jATroopsPanel.add(aTroops, BorderLayout.CENTER);
    jBTroopsPanel.add(bTroops, BorderLayout.CENTER);
    jKTroopsPanel.add(kTroops, BorderLayout.CENTER);
    jCTroopsPanel.add(cTroops, BorderLayout.CENTER);
    jRSettingsTab.add(rTroops, BorderLayout.CENTER);
    jXLabel1.setLineWrap(true);

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

        @Override
        public void valueChanged(ListSelectionEvent e) {
            showInfo(jFarmTable.getSelectedRowCount() + " Farm(en) gewhlt");
        }
    });

    coordSpinner = new CoordinateSpinner();
    coordSpinner.setEnabled(false);
    java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
    jFarmFromBarbarianSelectionDialog.getContentPane().add(coordSpinner, gridBagConstraints);

    // <editor-fold defaultstate="collapsed" desc=" Init HelpSystem ">
    if (!Constants.DEBUG) {
        GlobalOptions.getHelpBroker().enableHelpKey(getRootPane(), "farmManager",
                GlobalOptions.getHelpBroker().getHelpSet());
    } // </editor-fold>
}