Example usage for javax.swing.event ChangeListener ChangeListener

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

Introduction

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

Prototype

ChangeListener

Source Link

Usage

From source file:org.ut.biolab.medsavant.client.query.view.NumberSearchConditionEditorView.java

@Override
public void loadViewFromSearchConditionParameters(String encoding) throws ConditionRestorationException {

    double[] selectedValues;
    if (encoding == null) {
        selectedValues = null;//  w  ww  . j a va2  s . c  o  m
    } else {
        selectedValues = NumericConditionEncoder.unencodeConditions(encoding);
    }

    final double[] extremeValues = generator.getExtremeNumericValues();
    this.removeAll();

    if (extremeValues == null || (extremeValues[0] == 0 && extremeValues[1] == 0)) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.add(Box.createHorizontalGlue());
        p.add(new JLabel("<html>All values are blank for this condition.</html>"));
        p.add(Box.createHorizontalGlue());
        this.add(p);
        return;
    }

    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    JPanel p = ViewUtil.getClearPanel();
    ViewUtil.applyVerticalBoxLayout(p);

    JPanel labelPanel = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(labelPanel);
    labelPanel.add(Box.createHorizontalGlue());
    labelPanel.add(new JLabel("Filtering variants where " + item.getName() + ": "));
    labelPanel.add(Box.createHorizontalGlue());
    ButtonGroup group = new ButtonGroup();
    //JRadioButton isButton = new JRadioButton("is within the following range:");
    //JRadioButton nullButton = new JRadioButton("is missing");
    //group.add(isButton);
    //group.add(nullButton);

    final JCheckBox nullButton = new JCheckBox("include missing values");

    JPanel bp = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(bp);
    p.add(labelPanel);
    p.add(bp);
    add(p);
    final DecimalRangeSlider slider = new DecimalRangeSlider();

    slider.setMajorTickSpacing(5);
    slider.setMinorTickSpacing(1);

    final JTextField fromBox = new JTextField();
    final JTextField toBox = new JTextField();

    nullButton.setSelected(NumericConditionEncoder.encodesNull(encoding));

    nullButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                    ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                    extremeValues[1], nullButton.isSelected());
        }
    });

    fromBox.setMaximumSize(new Dimension(10000, 24));
    toBox.setMaximumSize(new Dimension(10000, 24));
    fromBox.setPreferredSize(new Dimension(FROM_TO_WIDTH, 24));
    toBox.setPreferredSize(new Dimension(FROM_TO_WIDTH, 24));
    fromBox.setMinimumSize(new Dimension(FROM_TO_WIDTH, 24));
    toBox.setMinimumSize(new Dimension(FROM_TO_WIDTH, 24));
    fromBox.setHorizontalAlignment(JTextField.RIGHT);
    toBox.setHorizontalAlignment(JTextField.RIGHT);

    final JLabel fromLabel = new JLabel();
    final JLabel toLabel = new JLabel();

    ViewUtil.makeMini(fromLabel);
    ViewUtil.makeMini(toLabel);

    JPanel fromToContainer = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(fromToContainer);
    fromToContainer.add(Box.createHorizontalGlue());
    fromToContainer.add(fromBox);
    fromToContainer.add(new JLabel(" - "));
    fromToContainer.add(toBox);
    fromToContainer.add(Box.createHorizontalGlue());

    JPanel minMaxContainer = ViewUtil.getClearPanel();
    minMaxContainer.setLayout(new BoxLayout(minMaxContainer, BoxLayout.X_AXIS));

    JPanel sliderContainer = ViewUtil.getClearPanel();
    sliderContainer.setLayout(new BoxLayout(sliderContainer, BoxLayout.Y_AXIS));
    sliderContainer.add(slider);

    JPanel nullValueContainer = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(nullValueContainer);
    nullValueContainer.add(Box.createHorizontalGlue());
    nullValueContainer.add(nullButton);
    nullButton.setBackground(nullValueContainer.getBackground()); //fixes a windows issue.
    nullValueContainer.add(Box.createHorizontalGlue());

    JPanel labelContainer = ViewUtil.getClearPanel();
    labelContainer.setLayout(new BoxLayout(labelContainer, BoxLayout.X_AXIS));
    labelContainer.add(fromLabel);
    labelContainer.add(Box.createHorizontalGlue());
    labelContainer.add(toLabel);
    sliderContainer.add(labelContainer);
    minMaxContainer.add(Box.createHorizontalGlue());
    minMaxContainer.add(sliderContainer);
    minMaxContainer.add(Box.createHorizontalGlue());

    add(fromToContainer);
    add(minMaxContainer);
    add(nullValueContainer);
    add(Box.createVerticalBox());

    slider.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (slider.isEnabled()) {
                fromBox.setText(ViewUtil.numToString(slider.getLow()));
                toBox.setText(ViewUtil.numToString(slider.getHigh()));
                encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                        ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                        extremeValues[1], nullButton.isSelected());
            }
        }
    });

    final KeyListener keyListener = new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_ENTER) {
                Range selectedRage = new Range(getNumber(fromBox.getText()), getNumber(toBox.getText()));
                setSelectedValues(slider, fromBox, toBox, selectedRage);
            }
        }

        private double getNumber(String s) {
            try {
                return Double.parseDouble(s.replaceAll(",", ""));
            } catch (NumberFormatException ignored) {
                return 0;
            }
        }
    };

    CaretListener caretListener = new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent ce) {
            if (!isAdjustingSlider) {
                try {
                    encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                            ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                            extremeValues[1], nullButton.isSelected());
                } catch (Exception e) {
                }
            }
        }
    };

    fromBox.addKeyListener(keyListener);

    toBox.addKeyListener(keyListener);

    fromBox.addCaretListener(caretListener);

    toBox.addCaretListener(caretListener);

    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            isAdjustingSlider = true;
            fromBox.setText(ViewUtil.numToString(slider.getLow()));
            toBox.setText(ViewUtil.numToString(slider.getHigh()));
            isAdjustingSlider = false;
        }
    });

    JPanel bottomContainer = new JPanel();

    bottomContainer.setLayout(new BoxLayout(bottomContainer, BoxLayout.X_AXIS));

    bottomContainer.add(Box.createHorizontalGlue());

    add(bottomContainer);

    setExtremeValues(slider, fromLabel, toLabel, fromBox, toBox, 0,
            new Range(extremeValues[0], extremeValues[1]));

    if (encoding != null) {
        double[] d = NumericConditionEncoder.unencodeConditions(encoding);
        setSelectedValues(slider, fromBox, toBox, new Range(d[0], d[1]));
    }
}

From source file:pipeline.GUI_utils.ListOfPointsView.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from ww  w. j a va2 s.c  om
public void show() {
    if (frame != null)
        frame.toFront();
    if (table == null) {
        spreadsheetEngine = new DependencyEngine(new BasicEngineProvider());
        setupTableModel(points);
        silenceUpdates.incrementAndGet();
        table = new JXTablePerColumnFiltering(tableModel);

        table.setRolloverEnabled(true);
        // table.setDragEnabled(true);
        table.setFillsViewportHeight(false);
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.setShowGrid(true);
        table.setShowHorizontalLines(true);
        table.setColumnSelectionAllowed(true);
        table.setRowSelectionAllowed(true);
        table.setColumnControlVisible(true);
        table.setHighlighters(new Highlighter[] { HighlighterFactory.createAlternateStriping() });

        table.addPropertyChangeListener("horizontalScrollEnabled", new PropertyChangeListener() {

            JViewport viewPort, filteringViewPort, columnDescViewPort;
            int lastX;

            ChangeListener scrollListener = new ChangeListener() {

                @Override
                public void stateChanged(ChangeEvent e) {
                    if (viewPort == null || filteringViewPort == null) {
                        return;
                    }
                    Point position = viewPort.getViewPosition();
                    if (position.x == lastX) {
                        return;
                    }
                    filteringViewPort.setViewPosition(position);
                    columnDescViewPort.setViewPosition(position);
                    lastX = position.x;
                }

            };

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (viewPort != null) {
                    viewPort.removeChangeListener(scrollListener);
                }
                if (evt.getNewValue().equals(true)) {
                    viewPort = getTableViewPort(table);
                    if (viewPort == null) {
                        return;
                    }
                    table.filteringTable.setHorizontalScrollEnabled(true);
                    table.tableForColumnDescriptions.setHorizontalScrollEnabled(true);
                    table.updateFilteringTableSetup();
                    filteringViewPort = getTableViewPort(table.filteringTable);
                    columnDescViewPort = getTableViewPort(table.tableForColumnDescriptions);
                    viewPort.addChangeListener(scrollListener);
                    scrollListener.stateChanged(null);
                } else {
                    table.filteringTable.setHorizontalScrollEnabled(false);
                    table.tableForColumnDescriptions.setHorizontalScrollEnabled(false);
                }
            }
        });

        modelForColumnDescriptions = new dataModelAllEditable(1, tableModel.getColumnCount());
        Vector<String> rowVector0 = (Vector<String>) modelForColumnDescriptions.getDataVector().get(0);
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            rowVector0.setElementAt(tableModel.getColumnName(j), j);
        }

        boolean done;
        do {
            done = true;
            for (TableColumn i : table.getColumns(true)) {
                TableColumnExt iCast = (TableColumnExt) i;
                if (iCast.getTitle().equals("Class") || iCast.getTitle().equals("c")
                        || iCast.getTitle().equals("t") || iCast.getTitle().equals("clusterID")
                        || iCast.getTitle().equals("userCell 2") || iCast.getTitle().equals("userCell 3")) {
                    if (iCast.isVisible()) {
                        iCast.setVisible(false);
                        done = false;
                        break;
                    }
                }
            }
        } while (!done);

        SwingUtilities.invokeLater(modelForColumnDescriptions::fireTableDataChanged);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(2000, 2000));

        updateColumnDescriptions();
        silenceUpdates.decrementAndGet();

        setSpreadsheetColumnEditorAndRenderer();

        tableForColumnDescriptions = new JXTable(modelForColumnDescriptions);
        table.tableForColumnDescriptions = tableForColumnDescriptions;

        JScrollPane jScrollPaneForNames = new JScrollPane(tableForColumnDescriptions);
        jScrollPaneForNames.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        JButton createScatterPlotButton = new JButton("Scatter plot from selected columns");
        controlPanel.add(createScatterPlotButton);
        createScatterPlotButton.setActionCommand("Scatter plot from selected columns");
        createScatterPlotButton.addActionListener(this);

        realTimeUpdateCheckbox = new JCheckBox("Update display in real time");
        controlPanel.add(realTimeUpdateCheckbox);
        realTimeUpdateCheckbox.setActionCommand("Update display in real time");
        realTimeUpdateCheckbox.addActionListener(this);

        JButton forceUpdate = new JButton("Force display update");
        controlPanel.add(forceUpdate);
        forceUpdate.setActionCommand("Force display update");
        forceUpdate.addActionListener(this);

        JButton extendFormula = new JButton("Extend formula to column");
        controlPanel.add(extendFormula);
        extendFormula.setActionCommand("Extend formula to column");
        extendFormula.addActionListener(this);

        JButton saveFormulas = new JButton("Save user formulas...");
        saveFormulas.addActionListener(this);
        saveFormulas.setActionCommand("Save user formulas");
        controlPanel.add(saveFormulas);

        JButton reloadFormulas = new JButton("Reload user formulas...");
        reloadFormulas.addActionListener(this);
        reloadFormulas.setActionCommand("Reload user formulas");
        controlPanel.add(reloadFormulas);

        controlPanel.add(new JLabel("Color with:"));
        coloringComboBox = new JComboBox();
        controlPanel.add(coloringComboBox);
        DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) coloringComboBox.getModel();
        coloringComboBox.addActionListener(this);

        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            comboBoxModel.addElement(tableModel.getColumnName(i));
        }

        JButton saveTableToFile = new JButton("Save table to file");
        controlPanel.add(saveTableToFile);
        saveTableToFile.setActionCommand("Save table to file");
        saveTableToFile.addActionListener(this);

        /*
        final JCheckBox useCalibration = new JCheckBox("Use calibration");
        useCalibration.addActionListener(e -> {
           if (points == null)
              return;
           boolean selected = useCalibration.isSelected();
           if (selected && !(points instanceof PluginIOCalibrable)) {
              Utils.displayMessage("Type " + points.getClass().getName() + " does not have calibration", true,
             LogLevel.ERROR);
              return;
           }
           PluginIOCalibrable calibrable = (PluginIOCalibrable) points;
           if (selected && (calibrable.getCalibration() == null)) {
              Utils.displayMessage("Calibration information is not present in the segmentation; one "
             + "way of adding it is to give the source image (with calibration) as an input "
             + "to the active contour plugin", true, LogLevel.ERROR);
              return;
           }
           float xyCalibration = selected ? ((float) calibrable.getCalibration().pixelWidth) : 0;
           float zCalibration = selected ? ((float) calibrable.getCalibration().pixelDepth) : 0;
           updateCalibration(xyCalibration, zCalibration);
        });
        PluginIOCalibrable calibrable = null;
        if (points instanceof PluginIOCalibrable)
           calibrable = (PluginIOCalibrable) points;
        boolean calibrationPresent = calibrable != null && calibrable.getCalibration() != null;
        useCalibration.setSelected(calibrationPresent);
        if (calibrationPresent) {
           updateCalibration((float) calibrable.getCalibration().pixelWidth,
          (float) calibrable.getCalibration().pixelDepth);
        }
        controlPanel.add(useCalibration);
        */

        frame = new JFrame(points.getName());
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        listener = new WindowListenerWeakRef(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                close();// So all references to data are nulled, to ensure garbage collection
            }

        });
        frame.addWindowListener(listener);

        frame.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = GridBagConstraints.RELATIVE;
        c.weighty = 0.75;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridheight = 1;

        frame.add(scrollPane, c);

        c.weighty = 0.0;
        JScrollPane scrollPane2 = new JScrollPane(table.filteringTable);
        scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane2.setMinimumSize(new Dimension(1, 250));
        frame.add(scrollPane2, c);

        c.weighty = 0.0;
        jScrollPaneForNames.setMinimumSize(new Dimension(1, 40));
        jScrollPaneForNames.setMaximumSize(new Dimension(9999999, 40));
        frame.add(jScrollPaneForNames, c);

        c.weighty = 0.0;
        c.fill = GridBagConstraints.HORIZONTAL;
        controlPanel.setMinimumSize(new Dimension(1, 80));
        frame.add(controlPanel, c);

        table.setHorizontalScrollEnabled(true);
        table.updateFilteringTableSetup();

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        frame.setSize((int) (0.67 * width), height / 2);
        frame.setLocation((int) (0.33 * width), height / 2);
        frame.setVisible(true);
    }

    if ((tableUpdateThread == null) || (!tableUpdateThread.isAlive())) {
        tableUpdateThread = new Thread(() -> {
            try {
                checkForDirtiness();
            } catch (Exception e) {
                Utils.log("Exception in ListOfPointsView GUI update thread", LogLevel.ERROR);
                Utils.printStack(e);
            }
        }, "ListOfPointsView GUI update thread");

        tableUpdateThread.start();
    }
}

From source file:pl.otros.logview.exceptionshandler.ShowErrorDialogExceptionHandler.java

protected JComponent createDialogView() {
    JPanel jPanel = new JPanel(new MigLayout());
    JLabel label = new JLabel("Do you want to send error report?");
    label.setFont(label.getFont().deriveFont(Font.BOLD));
    jPanel.add(label, "span 4, wrap, center");
    jPanel.add(new JLabel("Comment:"));
    commentTextArea = new JTextArea(10, 30);
    commentTextArea.setWrapStyleWord(true);
    commentTextArea.setLineWrap(true);//from  w w w.j  a  va  2s  . c o  m
    JScrollPane jScrollPane = new JScrollPane(commentTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jPanel.add(jScrollPane, "span 3, wrap");
    jPanel.add(new JLabel("Email (optional):"));
    emailTextField = new JTextField(30);
    jPanel.add(emailTextField, "span 3, wrap");

    jPanel.add(new JSeparator(), "span 4, wrap, grow");
    checkBoxUseProxy = new JCheckBox("Use HTTP proxy");
    proxyTf = new JTextField();
    proxyPortModel = new SpinnerNumberModel(80, 1, 256 * 256 - 1, 1);
    proxyUser = new JTextField();
    proxyPasswordField = new JPasswordField();
    proxySpinner = new JSpinner(proxyPortModel);

    jPanel.add(checkBoxUseProxy, "wrap");
    labelProxyHost = new JLabel("Proxy address");
    jPanel.add(labelProxyHost);
    jPanel.add(proxyTf, "wrap, span 3, grow");
    labelProxyPort = new JLabel("Proxy port");
    jPanel.add(labelProxyPort);
    jPanel.add(proxySpinner, "wrap");
    labelProxyUser = new JLabel("User");
    jPanel.add(labelProxyUser);
    jPanel.add(proxyUser, "grow");
    labelProxyPassword = new JLabel("Password");
    jPanel.add(labelProxyPassword);
    jPanel.add(proxyPasswordField, "grow");

    checkBoxUseProxy.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            setProxyEnabled(checkBoxUseProxy.isSelected());
        }
    });
    DataConfiguration c = otrosApplication.getConfiguration();
    proxyTf.setText(c.getString(ConfKeys.HTTP_PROXY_HOST, ""));
    proxyUser.setText(c.getString(ConfKeys.HTTP_PROXY_USER, ""));
    proxyPortModel.setValue(Integer.valueOf(c.getInt(ConfKeys.HTTP_PROXY_PORT, 80)));
    boolean useProxy = c.getBoolean(ConfKeys.HTTP_PROXY_USE, false);
    checkBoxUseProxy.setSelected(useProxy);
    setProxyEnabled(useProxy);

    return jPanel;
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private void initToolbar() {
    toolBar = new JToolBar();
    final JComboBox searchMode = new JComboBox(
            new String[] { "String contains search: ", "Regex search: ", "Query search: " });
    final SearchAction searchActionForward = new SearchAction(otrosApplication, SearchDirection.FORWARD);
    final SearchAction searchActionBackward = new SearchAction(otrosApplication, SearchDirection.REVERSE);
    searchFieldCbxModel = new DefaultComboBoxModel();
    searchField = new JXComboBox(searchFieldCbxModel);
    searchField.setEditable(true);//  ww  w  .j a v  a2 s  .  co m
    AutoCompleteDecorator.decorate(searchField);
    searchField.setMinimumSize(new Dimension(150, 10));
    searchField.setPreferredSize(new Dimension(250, 10));
    searchField.setToolTipText(
            "<HTML>Enter text to search.<BR/>" + "Enter - search next,<BR/>Alt+Enter search previous,<BR/>"
                    + "Ctrl+Enter - mark all found</HTML>");
    final DelayedSwingInvoke delayedSearchResultUpdate = new DelayedSwingInvoke() {
        @Override
        protected void performActionHook() {
            JTextComponent editorComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
            int stringEnd = editorComponent.getSelectionStart();
            if (stringEnd < 0) {
                stringEnd = editorComponent.getText().length();
            }
            try {
                String selectedText = editorComponent.getText(0, stringEnd);
                if (StringUtils.isBlank(selectedText)) {
                    return;
                }
                OtrosJTextWithRulerScrollPane<JTextPane> logDetailWithRulerScrollPane = otrosApplication
                        .getSelectedLogViewPanel().getLogDetailWithRulerScrollPane();
                MessageUpdateUtils.highlightSearchResult(logDetailWithRulerScrollPane,
                        otrosApplication.getAllPluginables().getMessageColorizers());
                RulerBarHelper.scrollToFirstMarker(logDetailWithRulerScrollPane);
            } catch (BadLocationException e) {
                LOGGER.log(Level.SEVERE, "Can't update search highlight", e);
            }
        }
    };
    JTextComponent searchFieldTextComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
    searchFieldTextComponent.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
        @Override
        protected void documentChanged(DocumentEvent e) {
            delayedSearchResultUpdate.performAction();
        }
    });
    final MarkAllFoundAction markAllFoundAction = new MarkAllFoundAction(otrosApplication);
    final SearchModeValidatorDocumentListener searchValidatorDocumentListener = new SearchModeValidatorDocumentListener(
            (JTextField) searchField.getEditor().getEditorComponent(), observer, SearchMode.STRING_CONTAINS);
    SearchMode searchModeFromConfig = configuration.get(SearchMode.class, "gui.searchMode",
            SearchMode.STRING_CONTAINS);
    final String lastSearchString;
    int selectedSearchMode = 0;
    if (searchModeFromConfig.equals(SearchMode.STRING_CONTAINS)) {
        selectedSearchMode = 0;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_STRING, "");
    } else if (searchModeFromConfig.equals(SearchMode.REGEX)) {
        selectedSearchMode = 1;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_REGEX, "");
    } else if (searchModeFromConfig.equals(SearchMode.QUERY)) {
        selectedSearchMode = 2;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_QUERY, "");
    } else {
        LOGGER.warning("Unknown search mode " + searchModeFromConfig);
        lastSearchString = "";
    }
    Component editorComponent = searchField.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        final JTextField sfTf = (JTextField) editorComponent;
        sfTf.getDocument().addDocumentListener(searchValidatorDocumentListener);
        sfTf.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
            @Override
            protected void documentChanged(DocumentEvent e) {
                try {
                    int length = e.getDocument().getLength();
                    if (length > 0) {
                        searchResultColorizer.setSearchString(e.getDocument().getText(0, length));
                    }
                } catch (BadLocationException e1) {
                    LOGGER.log(Level.SEVERE, "Error: ", e1);
                }
            }
        });
        sfTf.addKeyListener(new SearchFieldKeyListener(searchActionForward, sfTf));
        sfTf.setText(lastSearchString);
    }
    searchMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SearchMode mode = null;
            boolean validationEnabled = false;
            String confKey = null;
            String lastSearch = ((JTextField) searchField.getEditor().getEditorComponent()).getText();
            if (searchMode.getSelectedIndex() == 0) {
                mode = SearchMode.STRING_CONTAINS;
                searchValidatorDocumentListener.setSearchMode(mode);
                validationEnabled = false;
                searchMode.setToolTipText("Checking if log message contains string (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_STRING;
            } else if (searchMode.getSelectedIndex() == 1) {
                mode = SearchMode.REGEX;
                validationEnabled = true;
                searchMode
                        .setToolTipText("Checking if log message matches regular expression (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_REGEX;
            } else if (searchMode.getSelectedIndex() == 2) {
                mode = SearchMode.QUERY;
                validationEnabled = true;
                String querySearchTooltip = "<HTML>" + //
                "Advance search using SQL-like quries (i.e. level>=warning && msg~=failed && thread==t1)<BR/>" + //
                "Valid operator for query search is ==, ~=, !=, LIKE, EXISTS, <, <=, >, >=, &&, ||, ! <BR/>" + //
                "See wiki for more info<BR/>" + //
                "</HTML>";
                searchMode.setToolTipText(querySearchTooltip);
                confKey = ConfKeys.SEARCH_LAST_QUERY;
            }
            searchValidatorDocumentListener.setSearchMode(mode);
            searchValidatorDocumentListener.setEnable(validationEnabled);
            searchActionForward.setSearchMode(mode);
            searchActionBackward.setSearchMode(mode);
            markAllFoundAction.setSearchMode(mode);
            configuration.setProperty("gui.searchMode", mode);
            searchResultColorizer.setSearchMode(mode);
            List<Object> list = configuration.getList(confKey);
            searchFieldCbxModel.removeAllElements();
            for (Object o : list) {
                searchFieldCbxModel.addElement(o);
            }
            searchField.setSelectedItem(lastSearch);
        }
    });
    searchMode.setSelectedIndex(selectedSearchMode);
    final JCheckBox markFound = new JCheckBox("Mark search result");
    markFound.setMnemonic(KeyEvent.VK_M);
    searchField.addKeyListener(markAllFoundAction);
    configuration.addConfigurationListener(markAllFoundAction);
    JButton markAllFoundButton = new JButton(markAllFoundAction);
    final JComboBox markColor = new JComboBox(MarkerColors.values());
    markFound.setSelected(configuration.getBoolean("gui.markFound", true));
    markFound.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean selected = markFound.isSelected();
            searchActionForward.setMarkFound(selected);
            searchActionBackward.setMarkFound(selected);
            configuration.setProperty("gui.markFound", markFound.isSelected());
        }
    });
    markColor.setRenderer(new MarkerColorsComboBoxRenderer());
    //      markColor.addActionListener(new ActionListener() {
    //
    //         @Override
    //         public void actionPerformed(ActionEvent e) {
    //            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
    //            searchActionForward.setMarkerColors(markerColors);
    //            searchActionBackward.setMarkerColors(markerColors);
    //            markAllFoundAction.setMarkerColors(markerColors);
    //            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
    //            otrosApplication.setSelectedMarkColors(markerColors);
    //         }
    //      });
    markColor.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
            searchActionForward.setMarkerColors(markerColors);
            searchActionBackward.setMarkerColors(markerColors);
            markAllFoundAction.setMarkerColors(markerColors);
            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
            otrosApplication.setSelectedMarkColors(markerColors);
        }
    });
    markColor.getModel()
            .setSelectedItem(configuration.get(MarkerColors.class, "gui.markColor", MarkerColors.Aqua));
    buttonSearch = new JButton(searchActionForward);
    buttonSearch.setMnemonic(KeyEvent.VK_N);
    JButton buttonSearchPrev = new JButton(searchActionBackward);
    buttonSearchPrev.setMnemonic(KeyEvent.VK_P);
    enableDisableComponetsForTabs.addComponet(buttonSearch);
    enableDisableComponetsForTabs.addComponet(buttonSearchPrev);
    enableDisableComponetsForTabs.addComponet(searchField);
    enableDisableComponetsForTabs.addComponet(markFound);
    enableDisableComponetsForTabs.addComponet(markAllFoundButton);
    enableDisableComponetsForTabs.addComponet(searchMode);
    enableDisableComponetsForTabs.addComponet(markColor);
    toolBar.add(searchMode);
    toolBar.add(searchField);
    toolBar.add(buttonSearch);
    toolBar.add(buttonSearchPrev);
    toolBar.add(markFound);
    toolBar.add(markAllFoundButton);
    toolBar.add(markColor);
    JButton nextMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.FORWARD));
    nextMarked.setToolTipText(nextMarked.getText());
    nextMarked.setText("");
    nextMarked.setMnemonic(KeyEvent.VK_E);
    enableDisableComponetsForTabs.addComponet(nextMarked);
    toolBar.add(nextMarked);
    JButton prevMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.BACKWARD));
    prevMarked.setToolTipText(prevMarked.getText());
    prevMarked.setText("");
    prevMarked.setMnemonic(KeyEvent.VK_R);
    enableDisableComponetsForTabs.addComponet(prevMarked);
    toolBar.add(prevMarked);
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.SEVERE)));
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.SEVERE)));
}

From source file:pl.otros.logview.gui.LogViewPanel.java

private void addMessageFormatterOrColorizerToMenu(final JPopupMenu menu, final PluginableElement pluginable,
        final PluginableElementsContainer selectedPluginableContainer) {
    {//from w ww  .  j  av  a 2  s  .c  o m
        final JCheckBoxMenuItem boxMenuItem = new JCheckBoxMenuItem(pluginable.getName(),
                selectedPluginableContainer.contains(pluginable));
        boxMenuItem.setToolTipText(pluginable.getDescription());
        menu.add(boxMenuItem);
        boxMenuItem.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                if (boxMenuItem.isSelected() && !selectedPluginableContainer.contains(pluginable)) {
                    selectedPluginableContainer.addElement(pluginable);
                } else if (!boxMenuItem.isSelected() && selectedPluginableContainer.contains(pluginable)) {
                    selectedPluginableContainer.removeElement(pluginable);
                }
            }
        });
    }
}

From source file:plugins.tprovoost.Microscopy.MicroManagerForIcy.MMMainFrame.java

/**
 * Singleton pattern : private constructor Use instead.
 *//*  w w w . j  ava2 s.  c  o  m*/
private MMMainFrame() {
    super(NODE_NAME, false, true, false, true);
    instancing = true;
    // --------------
    // INITIALIZATION
    // --------------
    _sysConfigFile = "";
    _isConfigLoaded = false;
    _root = PluginPreferences.getPreferences().node(NODE_NAME);
    final MainFrame mainFrame = Icy.getMainInterface().getMainFrame();

    // --------------
    // PROGRESS FRAME
    // --------------
    ThreadUtil.invokeLater(new Runnable() {
        @Override
        public void run() {
            _progressFrame = new IcyFrame("", false, false, false, false);
            _progressBar = new JProgressBar();
            _progressBar.setString("Please wait while loading...");
            _progressBar.setStringPainted(true);
            _progressBar.setIndeterminate(true);
            _progressBar.setMinimum(0);
            _progressBar.setMaximum(1000);
            _progressBar.setBounds(50, 50, 100, 30);
            _progressFrame.setSize(300, 100);
            _progressFrame.setResizable(false);
            _progressFrame.add(_progressBar);
            _progressFrame.addToMainDesktopPane();
            loadConfig(true);
            if (_sysConfigFile == "") {
                instancing = false;
                return;
            }
            ThreadUtil.bgRun(new Runnable() {

                @Override
                public void run() {
                    while (!_isConfigLoaded) {
                        if (!instancing)
                            return;
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                        }
                    }
                    ThreadUtil.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            // --------------------
                            // START INITIALIZATION
                            // --------------------
                            if (_progressBar != null)
                                getContentPane().remove(_progressBar);
                            if (mCore == null) {
                                close();
                                return;
                            }

                            // ReportingUtils.setCore(mCore);
                            _afMgr = new AutofocusManager(MMMainFrame.this);
                            acqMgr = new AcquisitionManager();
                            PositionList posList = new PositionList();

                            _camera_label = MMCoreJ.getG_Keyword_CameraName();
                            if (_camera_label == null)
                                _camera_label = "";
                            try {
                                setPositionList(posList);
                            } catch (MMScriptException e1) {
                                e1.printStackTrace();
                            }
                            posListDlg_ = new PositionListDlg(mCore, MMMainFrame.this, _posList, null, dlg);
                            posListDlg_.setModalityType(ModalityType.APPLICATION_MODAL);

                            callback = new EventCallBackManager();
                            mCore.registerCallback(callback);

                            engine_ = new AcquisitionWrapperEngineIcy();
                            engine_.setParentGUI(MMMainFrame.this);
                            engine_.setCore(mCore, getAutofocusManager());
                            engine_.setPositionList(getPositionList());

                            setSystemMenuCallback(new MenuCallback() {

                                @Override
                                public JMenu getMenu() {
                                    JMenu toReturn = MMMainFrame.this.getDefaultSystemMenu();
                                    JMenuItem hconfig = new JMenuItem("Configuration Wizard");
                                    hconfig.setIcon(new IcyIcon("cog", MENU_ICON_SIZE));

                                    hconfig.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            if (!_pluginListEmpty && !ConfirmDialog.confirm("Are you sure ?",
                                                    "<html>Loading the Configuration Wizard will unload all the devices and pause all running acquisitions.</br> Are you sure you want to continue ?</html>"))
                                                return;
                                            notifyConfigAboutToChange(null);
                                            try {
                                                mCore.unloadAllDevices();
                                            } catch (Exception e1) {
                                                e1.printStackTrace();
                                            }
                                            String previous_config = _sysConfigFile;
                                            ConfiguratorDlg2 configurator = new ConfiguratorDlg2(mCore,
                                                    _sysConfigFile);
                                            configurator.setVisible(true);
                                            String res = configurator.getFileName();
                                            if (_sysConfigFile == "" || _sysConfigFile == res || res == "") {
                                                _sysConfigFile = previous_config;
                                                loadConfig();
                                            }
                                            refreshGUI();
                                            notifyConfigChanged(null);
                                        }
                                    });

                                    JMenuItem menuPxSizeConfigItem = new JMenuItem("Pixel Size Config");
                                    menuPxSizeConfigItem.setIcon(new IcyIcon("link", MENU_ICON_SIZE));
                                    menuPxSizeConfigItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
                                            InputEvent.SHIFT_DOWN_MASK | SHORTCUTKEY_MASK));
                                    menuPxSizeConfigItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            CalibrationListDlg dlg = new CalibrationListDlg(mCore);
                                            dlg.setDefaultCloseOperation(2);
                                            dlg.setParentGUI(MMMainFrame.this);
                                            dlg.setVisible(true);
                                            dlg.addWindowListener(new WindowAdapter() {
                                                @Override
                                                public void windowClosed(WindowEvent e) {
                                                    super.windowClosed(e);
                                                    notifyConfigChanged(null);
                                                }
                                            });
                                            notifyConfigAboutToChange(null);
                                        }
                                    });

                                    JMenuItem loadConfigItem = new JMenuItem("Load Configuration");
                                    loadConfigItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
                                            InputEvent.SHIFT_DOWN_MASK | SHORTCUTKEY_MASK));
                                    loadConfigItem.setIcon(new IcyIcon("folder_open", MENU_ICON_SIZE));
                                    loadConfigItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            loadConfig();
                                            initializeGUI();
                                            refreshGUI();
                                        }
                                    });
                                    JMenuItem saveConfigItem = new JMenuItem("Save Configuration");
                                    saveConfigItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
                                            InputEvent.SHIFT_DOWN_MASK | SHORTCUTKEY_MASK));
                                    saveConfigItem.setIcon(new IcyIcon("save", MENU_ICON_SIZE));
                                    saveConfigItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            saveConfig();
                                        }
                                    });
                                    JMenuItem advancedConfigItem = new JMenuItem("Advanced Configuration");
                                    advancedConfigItem.setIcon(new IcyIcon("wrench_plus", MENU_ICON_SIZE));
                                    advancedConfigItem.addActionListener(new ActionListener() {

                                        /**
                                         */
                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            new ToolTipFrame(
                                                    "<html><h3>About Advanced Config</h3><p>Advanced Configuration is a tool "
                                                            + "in which you fill some data <br/>about your configuration that some "
                                                            + "plugins may need to access to.<br/> Exemple: the real values of the magnification"
                                                            + "of your objectives.</p></html>",
                                                    "MM4IcyAdvancedConfig");
                                            if (advancedDlg == null)
                                                advancedDlg = new AdvancedConfigurationDialog();
                                            advancedDlg.setVisible(!advancedDlg.isVisible());
                                            advancedDlg.setLocationRelativeTo(mainFrame);
                                        }
                                    });
                                    JMenuItem loadPresetConfigItem = new JMenuItem(
                                            "Load Configuration Presets");
                                    loadPresetConfigItem.setIcon(new IcyIcon("doc_import", MENU_ICON_SIZE));
                                    loadPresetConfigItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            notifyConfigAboutToChange(null);
                                            loadPresets();
                                            notifyConfigChanged(null);
                                        }
                                    });
                                    JMenuItem savePresetConfigItem = new JMenuItem(
                                            "Save Configuration Presets");
                                    savePresetConfigItem.setIcon(new IcyIcon("doc_export", MENU_ICON_SIZE));
                                    savePresetConfigItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            savePresets();
                                        }
                                    });
                                    JMenuItem aboutItem = new JMenuItem("About");
                                    aboutItem.setIcon(new IcyIcon("info", MENU_ICON_SIZE));
                                    aboutItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            final JDialog dialog = new JDialog(mainFrame, "About");
                                            JPanel panel_container = new JPanel();
                                            panel_container
                                                    .setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
                                            JPanel center = new JPanel(new BorderLayout());
                                            final JLabel value = new JLabel("<html><body>"
                                                    + "<h2>About</h2><p>Micro-Manager for Icy is being developed by Thomas Provoost."
                                                    + "<br/>Copyright 2011, Institut Pasteur</p><br/>"
                                                    + "<p>This plugin is based on Micro-Manager v1.4.6. which is developed under the following license:<br/>"
                                                    + "<i>This software is distributed free of charge in the hope that it will be<br/>"
                                                    + "useful, but WITHOUT ANY WARRANTY; without even the implied<br/>"
                                                    + "warranty of merchantability or fitness for a particular purpose. In no<br/>"
                                                    + "event shall the copyright owner or contributors be liable for any direct,<br/>"
                                                    + "indirect, incidental spacial, examplary, or consequential damages.<br/>"
                                                    + "Copyright University of California San Francisco, 2007, 2008, 2009,<br/>"
                                                    + "2010. All rights reserved.</i>" + "</p>"
                                                    + "</body></html>");
                                            JLabel link = new JLabel(
                                                    "<html><a href=\"\">For more information, please follow this link.</a></html>");
                                            link.addMouseListener(new MouseAdapter() {
                                                @Override
                                                public void mousePressed(MouseEvent mouseevent) {
                                                    NetworkUtil.openBrowser(
                                                            "http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager");
                                                }
                                            });
                                            value.setSize(new Dimension(50, 18));
                                            value.setAlignmentX(SwingConstants.HORIZONTAL);
                                            value.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));

                                            center.add(value, BorderLayout.CENTER);
                                            center.add(link, BorderLayout.SOUTH);

                                            JPanel panel_south = new JPanel();
                                            panel_south.setLayout(new BoxLayout(panel_south, BoxLayout.X_AXIS));
                                            JButton btn = new JButton("OK");
                                            btn.addActionListener(new ActionListener() {

                                                @Override
                                                public void actionPerformed(ActionEvent actionevent) {
                                                    dialog.dispose();
                                                }
                                            });
                                            panel_south.add(Box.createHorizontalGlue());
                                            panel_south.add(btn);
                                            panel_south.add(Box.createHorizontalGlue());

                                            dialog.setLayout(new BorderLayout());
                                            panel_container.setLayout(new BorderLayout());
                                            panel_container.add(center, BorderLayout.CENTER);
                                            panel_container.add(panel_south, BorderLayout.SOUTH);
                                            dialog.add(panel_container, BorderLayout.CENTER);
                                            dialog.setResizable(false);
                                            dialog.setVisible(true);
                                            dialog.pack();
                                            dialog.setLocation(
                                                    (int) mainFrame.getSize().getWidth() / 2
                                                            - dialog.getWidth() / 2,
                                                    (int) mainFrame.getSize().getHeight() / 2
                                                            - dialog.getHeight() / 2);
                                            dialog.setLocationRelativeTo(mainFrame);
                                        }
                                    });
                                    JMenuItem propertyBrowserItem = new JMenuItem("Property Browser");
                                    propertyBrowserItem.setAccelerator(
                                            KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, SHORTCUTKEY_MASK));
                                    propertyBrowserItem.setIcon(new IcyIcon("db", MENU_ICON_SIZE));
                                    propertyBrowserItem.addActionListener(new ActionListener() {

                                        @Override
                                        public void actionPerformed(ActionEvent e) {
                                            editor.setVisible(!editor.isVisible());
                                        }
                                    });
                                    int idx = 0;
                                    toReturn.insert(hconfig, idx++);
                                    toReturn.insert(loadConfigItem, idx++);
                                    toReturn.insert(saveConfigItem, idx++);
                                    toReturn.insert(advancedConfigItem, idx++);
                                    toReturn.insertSeparator(idx++);
                                    toReturn.insert(loadPresetConfigItem, idx++);
                                    toReturn.insert(savePresetConfigItem, idx++);
                                    toReturn.insertSeparator(idx++);
                                    toReturn.insert(propertyBrowserItem, idx++);
                                    toReturn.insert(menuPxSizeConfigItem, idx++);
                                    toReturn.insertSeparator(idx++);
                                    toReturn.insert(aboutItem, idx++);
                                    return toReturn;
                                }
                            });

                            saveConfigButton_ = new JButton("Save Button");

                            // SETUP
                            _groupPad = new ConfigGroupPad();
                            _groupPad.setParentGUI(MMMainFrame.this);
                            _groupPad.setFont(new Font("", 0, 10));
                            _groupPad.setCore(mCore);
                            _groupPad.setParentGUI(MMMainFrame.this);
                            _groupButtonsPanel = new ConfigButtonsPanel();
                            _groupButtonsPanel.setCore(mCore);
                            _groupButtonsPanel.setGUI(MMMainFrame.this);
                            _groupButtonsPanel.setConfigPad(_groupPad);

                            // LEFT PART OF INTERFACE
                            _panelConfig = new JPanel();
                            _panelConfig.setLayout(new BoxLayout(_panelConfig, BoxLayout.Y_AXIS));
                            _panelConfig.add(_groupPad, BorderLayout.CENTER);
                            _panelConfig.add(_groupButtonsPanel, BorderLayout.SOUTH);
                            _panelConfig.setPreferredSize(new Dimension(300, 300));

                            // MIDDLE PART OF INTERFACE
                            _panel_cameraSettings = new JPanel();
                            _panel_cameraSettings.setLayout(new GridLayout(5, 2));
                            _panel_cameraSettings.setMinimumSize(new Dimension(100, 200));

                            _txtExposure = new JTextField();
                            try {
                                mCore.setExposure(90.0D);
                                _txtExposure.setText(String.valueOf(mCore.getExposure()));
                            } catch (Exception e2) {
                                _txtExposure.setText("90");
                            }
                            _txtExposure.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
                            _txtExposure.addKeyListener(new KeyAdapter() {
                                @Override
                                public void keyPressed(KeyEvent keyevent) {
                                    if (keyevent.getKeyCode() == KeyEvent.VK_ENTER)
                                        setExposure();
                                }
                            });
                            _panel_cameraSettings.add(new JLabel("Exposure [ms]: "));
                            _panel_cameraSettings.add(_txtExposure);

                            _combo_binning = new JComboBox();
                            _combo_binning.setMaximumRowCount(4);
                            _combo_binning.setMaximumSize(new Dimension(Integer.MAX_VALUE, 25));
                            _combo_binning.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    changeBinning();
                                }
                            });

                            _panel_cameraSettings.add(new JLabel("Binning: "));
                            _panel_cameraSettings.add(_combo_binning);

                            _combo_shutters = new JComboBox();
                            _combo_shutters.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent arg0) {
                                    try {
                                        if (_combo_shutters.getSelectedItem() != null) {
                                            mCore.setShutterDevice((String) _combo_shutters.getSelectedItem());
                                            _prefs.put(PREF_SHUTTER, (String) _combo_shutters
                                                    .getItemAt(_combo_shutters.getSelectedIndex()));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            _combo_shutters.setMaximumSize(new Dimension(Integer.MAX_VALUE, 25));
                            _panel_cameraSettings.add(new JLabel("Shutter : "));
                            _panel_cameraSettings.add(_combo_shutters);

                            ActionListener action_listener = new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    updateHistogram();
                                }
                            };

                            _cbAbsoluteHisto = new JCheckBox();
                            _cbAbsoluteHisto.addActionListener(action_listener);
                            _cbAbsoluteHisto.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent actionevent) {
                                    _comboBitDepth.setEnabled(_cbAbsoluteHisto.isSelected());
                                    _prefs.putBoolean(PREF_ABS_HIST, _cbAbsoluteHisto.isSelected());
                                }
                            });
                            _panel_cameraSettings.add(new JLabel("Display absolute histogram ?"));
                            _panel_cameraSettings.add(_cbAbsoluteHisto);

                            _comboBitDepth = new JComboBox(new String[] { "8-bit", "9-bit", "10-bit", "11-bit",
                                    "12-bit", "13-bit", "14-bit", "15-bit", "16-bit" });
                            _comboBitDepth.addActionListener(action_listener);
                            _comboBitDepth.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent actionevent) {
                                    _prefs.putInt(PREF_BITDEPTH, _comboBitDepth.getSelectedIndex());
                                }
                            });
                            _comboBitDepth.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
                            _comboBitDepth.setEnabled(false);
                            _panel_cameraSettings.add(new JLabel("Select your bit depth for abs. hitogram: "));
                            _panel_cameraSettings.add(_comboBitDepth);

                            // Acquisition
                            _panelAcquisitions = new JPanel();
                            _panelAcquisitions.setLayout(new BoxLayout(_panelAcquisitions, BoxLayout.Y_AXIS));

                            // Color settings
                            _panelColorChooser = new JPanel();
                            _panelColorChooser.setLayout(new BoxLayout(_panelColorChooser, BoxLayout.Y_AXIS));
                            painterPreferences = MicroscopePainterPreferences.getInstance();
                            painterPreferences.setPreferences(_prefs.node("paintersPreferences"));
                            painterPreferences.loadColors();

                            HashMap<String, Color> allColors = painterPreferences.getColors();
                            String[] allKeys = (String[]) allColors.keySet().toArray(new String[0]);
                            String[] columnNames = { "Painter", "Color", "Transparency" };
                            Object[][] data = new Object[allKeys.length][3];

                            for (int i = 0; i < allKeys.length; ++i) {
                                final int actualRow = i;
                                String actualKey = allKeys[i].toString();
                                data[i][0] = actualKey;
                                data[i][1] = allColors.get(actualKey);
                                final JSlider slider = new JSlider(0, 255, allColors.get(actualKey).getAlpha());
                                slider.addChangeListener(new ChangeListener() {

                                    @Override
                                    public void stateChanged(ChangeEvent changeevent) {
                                        painterTable.setValueAt(slider, actualRow, 2);
                                    }
                                });
                                data[i][2] = slider;
                            }
                            final AbstractTableModel tableModel = new JTableEvolvedModel(columnNames, data);
                            painterTable = new JTable(tableModel);
                            painterTable.getModel().addTableModelListener(new TableModelListener() {

                                @Override
                                public void tableChanged(TableModelEvent tablemodelevent) {
                                    if (tablemodelevent.getType() == TableModelEvent.UPDATE) {
                                        int row = tablemodelevent.getFirstRow();
                                        int col = tablemodelevent.getColumn();
                                        String columnName = tableModel.getColumnName(col);
                                        String painterName = (String) tableModel.getValueAt(row, 0);
                                        if (columnName.contains("Color")) {
                                            // New color value
                                            int alpha = painterPreferences.getColor(painterName).getAlpha();
                                            Color coloNew = (Color) tableModel.getValueAt(row, 1);
                                            painterPreferences.setColor(painterName, new Color(coloNew.getRed(),
                                                    coloNew.getGreen(), coloNew.getBlue(), alpha));
                                        } else if (columnName.contains("Transparency")) {
                                            // New alpha value
                                            Color c = painterPreferences.getColor(painterName);
                                            int alphaValue = ((JSlider) tableModel.getValueAt(row, 2))
                                                    .getValue();
                                            painterPreferences.setColor(painterName, new Color(c.getRed(),
                                                    c.getGreen(), c.getBlue(), alphaValue));
                                        }
                                        /*
                                         * for (int i = 0; i <
                                         * tableModel.getRowCount(); ++i) { try {
                                         * String painterName = (String)
                                         * tableModel.getValueAt(i, 0); Color c =
                                         * (Color) tableModel.getValueAt(i, 1); int
                                         * alphaValue; if (ASpinnerChanged &&
                                         * tablemodelevent.getFirstRow() == i) {
                                         * alphaValue = ((JSlider)
                                         * tableModel.getValueAt(i, 2)).getValue();
                                         * } else { alphaValue =
                                         * painterPreferences.getColor
                                         * (painterPreferences
                                         * .getPainterName(i)).getAlpha(); }
                                         * painterPreferences.setColor(painterName,
                                         * new Color(c.getRed(), c.getGreen(),
                                         * c.getBlue(), alphaValue)); } catch
                                         * (Exception e) { System.out.println(
                                         * "error with painter table update"); } }
                                         */
                                    }
                                }
                            });
                            painterTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
                            painterTable.setFillsViewportHeight(true);

                            // Create the scroll pane and add the table to it.
                            JScrollPane scrollPane = new JScrollPane(painterTable);

                            // Set up renderer and editor for the Favorite Color
                            // column.
                            painterTable.setDefaultRenderer(Color.class, new ColorRenderer(true));
                            painterTable.setDefaultEditor(Color.class, new ColorEditor());

                            painterTable.setDefaultRenderer(JSlider.class, new SliderRenderer(0, 255));
                            painterTable.setDefaultEditor(JSlider.class, new SliderEditor());

                            _panelColorChooser.add(scrollPane);
                            _panelColorChooser.add(Box.createVerticalGlue());

                            _mainPanel = new JPanel();
                            _mainPanel.setLayout(new BorderLayout());

                            // EDITOR
                            // will refresh the data and verify if any change
                            // occurs.
                            // editor = new PropertyEditor(MMMainFrame.this);
                            // editor.setCore(mCore);
                            // editor.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
                            // editor.addToMainDesktopPane();
                            // editor.refresh();
                            // editor.start();

                            editor = new PropertyEditor();
                            editor.setGui(MMMainFrame.this);
                            editor.setCore(mCore);
                            editor.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
                            // editor.addToMainDesktopPane();
                            // editor.refresh();
                            // editor.start();

                            add(_mainPanel);
                            initializeGUI();
                            loadPreferences();
                            refreshGUI();
                            setResizable(true);
                            addToMainDesktopPane();
                            instanced = true;
                            instancing = false;
                            _singleton = MMMainFrame.this;
                            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                            addFrameListener(new IcyFrameAdapter() {
                                @Override
                                public void icyFrameClosing(IcyFrameEvent e) {
                                    customClose();
                                }
                            });
                            acceptListener = new AcceptListener() {

                                @Override
                                public boolean accept(Object source) {
                                    close();
                                    return _pluginListEmpty;
                                }
                            };

                            adapter = new MainAdapter() {

                                @Override
                                public void sequenceOpened(MainEvent event) {
                                    updateHistogram();
                                }

                            };
                            Icy.getMainInterface().addCanExitListener(acceptListener);
                            Icy.getMainInterface().addListener(adapter);
                        }
                    });
                }
            });
        }
    });
}

From source file:Provider.GoogleMapsStatic.TestUI.MySample.java

/**
 * @author Nazmul//from   w  w  w .  j  av  a  2s  .  com
 */
private void initComponents() {
    // JFormDesigner - Component initialization - DO NOT MODIFY
    // //GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    ttfSizeW = new JTextField("512");
    ttfLat = new JTextField("45.5");
    btnGetMap = new JButton("Get Map");
    btnQuit = new JButton("Quit");
    ttfSizeH = new JTextField("512");
    ttfLon = new JTextField("-73.55");
    ttfZoom = new JTextField("14");
    ttaStatus = new JTextArea();
    checkboxRecvStatus = new JCheckBox();
    checkboxSendStatus = new JCheckBox();
    ttfProgressMsg = new JTextField();
    progressBar = new JProgressBar();
    imgLbl = new JLabel();

    /***
     * @author Dhgiang, jpmolinamatute
     * Created a slider, zoom in/out buttons, conbo box (drop down listbox) for city selection,
     * a panel to group the zoom buttons and the slider bar
     */
    slider = new JSlider(0, 19, 14);
    controlPanel = new JPanel(new GridBagLayout()); // controlPanel was created by jpmolinamatute 
    cities = new JComboBox<Object>(new String[] { "Montreal", "Toronto", // the place setting where the combo box is now used to be a text field
            "Vancouver", "New York City", "Caracas", "Hong Kong" }); // for license key, but it was removed to accommodate space for combo box 
    // @author Dhgiang

    JPanel panel1 = new JPanel();
    JPanel contentPanel = new JPanel();
    JPanel btnPanel = new JPanel();
    JPanel dialogPane = new JPanel();

    JLabel label1 = new JLabel("Select City"); // this used to be the label for license key, it was changed to label as 'select city'
    JLabel label2 = new JLabel("Size Width");
    JLabel label3 = new JLabel("Size Height");
    JLabel label4 = new JLabel("Latitude");
    JLabel label5 = new JLabel("Longitude");
    JLabel label6 = new JLabel("Zoom");

    JButton btnZoomIn = new JButton("-");
    JButton btnZoomOut = new JButton("+");

    /***
     * @author jpmolinamatute
     * Created 8 cardinal points: N,NE,NW; S,SE,SW; E, W; 
     */
    JButton btnSE = new JButton("SE");
    JButton btnS = new JButton("S");
    JButton btnSW = new JButton("SW");
    JButton btnE = new JButton("E");
    JButton btnW = new JButton("W");
    JButton btnNE = new JButton("NE");
    JButton btnN = new JButton("N");
    JButton btnNW = new JButton("NW");

    /*** 
     * @author JPMolinaMatute
     * Creaetd a spaceControl GridBagConstraints object to manage 
     * the cardinal points, and add KeyListener so users can use the
     * 8 cardinal keys on the num pad; initialize dimensions
     * 
     */
    GridBagConstraints spaceControl = new GridBagConstraints();
    spaceControl.insets = new Insets(5, 5, 5, 5);
    controlPanel.addKeyListener(this);
    controlPanel.setSize(new Dimension(512, 512));
    // ---- My Combo Boxes for different city coordinates ----//

    // ======== this ========
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setTitle("Google Static Maps");
    setIconImage(null);
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());

    // ======== dialogPane ========
    {
        dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
        dialogPane.setOpaque(false);
        dialogPane.setLayout(new BorderLayout());

        // ======== contentPanel ========
        {
            contentPanel.setOpaque(false);
            contentPanel.setLayout(new TableLayout(
                    new double[][] { { TableLayoutConstants.FILL }, { TableLayoutConstants.PREFERRED,
                            TableLayoutConstants.FILL, TableLayoutConstants.PREFERRED } }));
            ((TableLayout) contentPanel.getLayout()).setHGap(5);
            ((TableLayout) contentPanel.getLayout()).setVGap(5);

            // ======== panel1 ========
            {
                panel1.setOpaque(false);
                panel1.setBorder(new CompoundBorder(
                        new TitledBorder("Configure the inputs to Google Static Maps"), Borders.DLU2_BORDER));
                panel1.setLayout(new TableLayout(
                        new double[][] { { 0.17, 0.17, 0.17, 0.17, 0.05, TableLayoutConstants.FILL },
                                { TableLayoutConstants.PREFERRED, TableLayoutConstants.PREFERRED,
                                        TableLayoutConstants.PREFERRED } }));
                ((TableLayout) panel1.getLayout()).setHGap(5);
                ((TableLayout) panel1.getLayout()).setVGap(5);

                label1.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label1, new TableLayoutConstraints(0, 2, 0, 2, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));
                // ---- label2 ----
                label2.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label2, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- ttfSizeW ----

                panel1.add(ttfSizeW, new TableLayoutConstraints(1, 0, 1, 0, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- label4 ----

                label4.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label4, new TableLayoutConstraints(2, 0, 2, 0, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- ttfLat ----

                panel1.add(ttfLat, new TableLayoutConstraints(3, 0, 3, 0, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- btnGetMap ----
                btnGetMap.setHorizontalAlignment(SwingConstants.LEFT);
                btnGetMap.setMnemonic('G');
                btnGetMap.setActionCommand("getMap");
                btnGetMap.addActionListener(this);
                panel1.add(btnGetMap, new TableLayoutConstraints(5, 0, 5, 0, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- label3 ----
                label3.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label3, new TableLayoutConstraints(0, 1, 0, 1, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- ttfSizeH ----

                panel1.add(ttfSizeH, new TableLayoutConstraints(1, 1, 1, 1, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- label5 ----
                label5.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label5, new TableLayoutConstraints(2, 1, 2, 1, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- ttfLon ----

                panel1.add(ttfLon, new TableLayoutConstraints(3, 1, 3, 1, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- btnQuit ----
                btnQuit.setMnemonic('Q');
                btnQuit.setHorizontalAlignment(SwingConstants.LEFT);
                btnQuit.setHorizontalTextPosition(SwingConstants.RIGHT);
                btnQuit.setActionCommand("quit");
                btnQuit.addActionListener(this);

                panel1.add(btnQuit, new TableLayoutConstraints(5, 1, 5, 1, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                /***
                 * @author Dhgiang
                 * Added an anonymous inner class for ItemLister and event handling for the combo box
                 * Used the switch case condition handling to set coordinates based on the city selected
                 * Juan helped modified this method by adding the startTaskAction() at the end so 
                 * users don't have to click on Get Map button.
                 */

                cities.setSelectedIndex(0); // initialize the city selection item to 0 (or the first item)      

                cities.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent e) {
                        Integer z = cities.getSelectedIndex();
                        switch (z) {
                        case 0:
                            ttfLat.setText("45.5");
                            ttfLon.setText("-73.55");
                            break;
                        case 1:
                            ttfLat.setText("43.65");
                            ttfLon.setText("-79.38");
                            break;
                        case 2:
                            ttfLat.setText("49.2505");
                            ttfLon.setText("-123.1119");
                            break;
                        case 3:
                            ttfLat.setText("40.7142");
                            ttfLon.setText("-74.0064");
                            break;
                        case 4:
                            ttfLat.setText("10.4901");
                            ttfLon.setText("-66.9151");
                            break;
                        case 5:
                            ttfLat.setText("22.257");
                            ttfLon.setText("114.2");
                            break;
                        default:
                            break;
                        }
                        startTaskAction();
                    }
                });

                /***
                 * @author Dhgiang
                 * Added the combo box to the panel
                 */
                panel1.add(cities, new TableLayoutConstraints(1, 2, 1, 2, TableLayoutConstraints.FULL,
                        TableLayoutConstraints.FULL));

                // ---- label6 ----
                label6.setHorizontalAlignment(SwingConstants.RIGHT);
                panel1.add(label6, new TableLayoutConstraints(2, 2, 2, 2, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));

                // ---- ttfZoom ----

                panel1.add(ttfZoom, new TableLayoutConstraints(3, 2, 3, 2, TableLayoutConstants.FULL,
                        TableLayoutConstants.FULL));
            }
            {
                btnPanel.setOpaque(false);
                btnPanel.setLayout(new GridLayout(0, 3));

                /****
                 * @author Dhgiang
                 * Initializing the zoom IN / OUT buttons with proper parameters and
                 * adding them to the btnPanel of Panel1 (panel within a panel)
                 */
                // ---- btnZoomIn ----
                btnZoomIn.setHorizontalAlignment(SwingConstants.LEFT);
                btnZoomIn.setHorizontalTextPosition(SwingConstants.RIGHT);
                btnZoomIn.setActionCommand("Zoomin");
                btnZoomIn.addActionListener(this);
                btnPanel.add(btnZoomIn, new TableLayoutConstraints(5, 2, 5, 2, TableLayoutConstraints.FULL,
                        TableLayoutConstraints.FULL));

                // ---- btnZoomOut ----
                btnZoomOut.setHorizontalAlignment(SwingConstants.RIGHT);
                btnZoomOut.setHorizontalTextPosition(SwingConstants.RIGHT);
                btnZoomOut.setActionCommand("Zoomout");
                btnZoomOut.addActionListener(this);

                btnPanel.add(btnZoomOut, new TableLayoutConstraints(5, 2, 5, 2, TableLayoutConstraints.FULL,
                        TableLayoutConstraints.FULL));

                /***
                 * @author Dhgiang
                 * Having created a new JSlider slider object, maximum & minimum values 
                 * are initialized along with incremental values
                 * 
                 */
                // ---- slider -----
                slider.setMaximum(19);
                slider.setMinimum(0);
                slider.setPaintTicks(true);
                slider.setMajorTickSpacing(19);
                slider.setMinorTickSpacing(1);
                slider.setPaintTrack(false);
                slider.createStandardLabels(4, 0);

                /***
                 * @author Dhgiang
                 * Added a ChangeListener to the slider so that 
                 * 1) the slider moves left if (-) button is clicked, slider moves right if (+) is clicked
                 * 2) and zoom values will increase or decrease if slider bar is shifted left or right accordingly
                 * 3) after the user releases the click button, the map will display automatically with the values
                 *    set by the slider bar, without having the user to click on get map button
                 */
                slider.addChangeListener(new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent arg0) {
                        Integer a = slider.getValue();

                        if (a >= 0 && a <= 19) {
                            ttfZoom.setText(a.toString());
                            startTaskAction();
                        }

                    }

                });
                slider.setBorder(null);

                /***
                 * @author Dhgiang
                 * Added the slider bar to the button panel
                 */
                btnPanel.add(slider, new TableLayoutConstraints(5, 2, 5, 2, TableLayoutConstraints.FULL,
                        TableLayoutConstraints.FULL));
            }

            /***
             * @author Dhgiang
             * Adding the button panel to panel1
             */
            panel1.add(btnPanel, new TableLayoutConstraints(5, 2, 5, 2, TableLayoutConstraints.FULL,
                    TableLayoutConstraints.FULL));
            contentPanel.add(panel1, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstants.FULL,
                    TableLayoutConstants.FULL));

            /***
             * @author jpmolinamatute
             * Initializing coordinates for the cardinal points
             * Adding the cardinal points button to the control panel
             */
            // ---- Cardinals points -----
            btnNW.setActionCommand("Northwest");
            btnNW.addActionListener(this);
            spaceControl.gridx = 0;
            spaceControl.gridy = 0;
            controlPanel.add(btnNW, spaceControl);

            btnN.setActionCommand("North");
            btnN.addActionListener(this);
            spaceControl.gridx = 3;
            spaceControl.gridy = 0;
            controlPanel.add(btnN, spaceControl);

            btnNE.setActionCommand("Northeast");
            btnNE.addActionListener(this);
            spaceControl.gridx = 6;
            spaceControl.gridy = 0;
            controlPanel.add(btnNE, spaceControl);

            btnW.setActionCommand("West");
            btnW.addActionListener(this);
            spaceControl.gridx = 0;
            spaceControl.gridy = 3;
            controlPanel.add(btnW, spaceControl);

            spaceControl.gridx = 3;
            spaceControl.gridy = 3;
            controlPanel.add(imgLbl, spaceControl);

            btnE.setActionCommand("East");
            btnE.addActionListener(this);
            spaceControl.gridx = 6;
            spaceControl.gridy = 3;
            controlPanel.add(btnE, spaceControl);

            btnSW.setActionCommand("Southwest");
            btnSW.addActionListener(this);
            spaceControl.gridx = 0;
            spaceControl.gridy = 6;
            controlPanel.add(btnSW, spaceControl);

            btnS.setActionCommand("South");
            btnS.addActionListener(this);
            spaceControl.gridx = 3;
            spaceControl.gridy = 6;
            controlPanel.add(btnS, spaceControl);

            btnSE.setActionCommand("Southeast");
            btnSE.addActionListener(this);
            spaceControl.gridx = 6;
            spaceControl.gridy = 6;
            controlPanel.add(btnSE, spaceControl);

            contentPanel.add(controlPanel, new TableLayoutConstraints(0, 1, 0, 1, TableLayoutConstants.FULL,
                    TableLayoutConstants.FULL));

        }
        dialogPane.add(contentPanel, BorderLayout.CENTER);
    }

    contentPane.add(dialogPane, BorderLayout.CENTER);
    setSize(700, 800);

    setLocationRelativeTo(null);
}

From source file:pt.lsts.neptus.console.plugins.ImageLayers.java

private void rebuildControls() {
    scroll.removeAll();//ww  w  .  j  ava 2s .  c  o m

    for (final ImageLayer il : layers) {
        scroll.add(new JLabel(il.getName()));
        final JSlider slider = new JSlider(0, 1000, (int) (il.getTransparency() * 1000));
        slider.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                il.setTransparency(slider.getValue() / 1000.0);
            }
        });
        slider.setMinimumSize(new Dimension(20, 20));
        scroll.add(slider);
    }
    scroll.doLayout();
    scroll.revalidate();
}

From source file:pt.lsts.neptus.plugins.sunfish.awareness.SituationAwareness.java

@Override
public void initInteraction() {
    Reflections reflections = new Reflections(getClass().getPackage().getName());

    for (Class<? extends ILocationProvider> c : reflections.getSubTypesOf(ILocationProvider.class)) {
        try {//from   ww w .j a  v a2  s .  co m
            ILocationProvider localizer = c.newInstance();
            updaters.addAll(PeriodicUpdatesService.inspect(localizer));
            localizer.onInit(this);
            localizers.add(localizer);
        } catch (Exception e) {
            NeptusLog.pub().error(e);
        }
    }

    for (IPeriodicUpdates upd : updaters) {
        PeriodicUpdatesService.register(upd);
    }

    if (getConsole() != null)
        for (MapPanel map : getConsole().getSubPanelsOfClass(MapPanel.class))
            map.addLayer(this);

    loadImages();
    propertiesChanged();

    Thread t = new Thread("Asset Properties Loader") {
        public void run() {
            fetchAssetProperties();

            try {
                Collection<AssetPosition> dailyPositions = PositionHistory.getHistory();
                for (AssetPosition p : dailyPositions) {
                    p.setSource("Daily Positions CSV");
                    addAssetPosition(p);
                }
                slider.setValue(slider.getUpperValue() - 3600 * 24);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.setDaemon(true);
    t.start();

    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            minTimeLabel.setText(fmt.format(new Date(slider.getValue() * 1000l)));
            maxTimeLabel.setText(fmt.format(new Date(slider.getUpperValue() * 1000l)));
            oldestTimestampSelection = slider.getValue() * 1000l;
            newestTimestampSelection = (slider.getValue() + slider.getExtent()) * 1000l;
            if (slider.getUpperValue() - slider.getValue() < 3600) {
                slider.setUpperValue(Math.min(slider.getMaximum(), slider.getValue() + 3600));
            }

        }
    });
}

From source file:richtercloud.reflection.form.builder.components.AmountMoneyPanel.java

/**
 * Creates a new AmountMoneyPanel with {@link #DEFAULT_CURRENCIES} and
 * {@code additionalCurrencies}.//  w  w  w .j ava2  s. c o  m
 * @param amountMoneyCurrencyStorage
 * @param amountMoneyUsageStatisticsStorage
 * @param amountMoneyExchangeRateRetriever
 * @param messageHandler
 * @throws richtercloud.reflection.form.builder.components.AmountMoneyCurrencyStorageException
 */
public AmountMoneyPanel(AmountMoneyCurrencyStorage amountMoneyCurrencyStorage,
        AmountMoneyUsageStatisticsStorage amountMoneyUsageStatisticsStorage,
        AmountMoneyExchangeRateRetriever amountMoneyExchangeRateRetriever, MessageHandler messageHandler)
        throws AmountMoneyCurrencyStorageException {
    this.messageHandler = messageHandler;
    Set<Currency> exchangeRateRetrieverSupportedCurrencies = amountMoneyExchangeRateRetriever
            .getSupportedCurrencies();
    for (Currency currency : amountMoneyCurrencyStorage.getCurrencies()) {
        if (!exchangeRateRetrieverSupportedCurrencies.contains(currency)) {
            try {
                currency.getExchangeRate();
            } catch (ConversionException ex) {
                throw new IllegalArgumentException(String.format(
                        "Currency %s isn't supported by exchange rate retriever and doesn't have an exchange rate set",
                        currency));
            }
        }
        currencyComboBoxModel.addElement(currency);
    }
    initComponents();
    ((SpinnerNumberModel) amountIntegerSpinner.getModel())
            .setMaximum(((long) (Double.MAX_VALUE * MINIMAL_STEP)));
    //cast to long is necessary to make ChangeListener of
    //amountIntegerSpinner be notified
    this.amountIntegerSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) {
                updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue()));
            }
        }
    });
    this.amountDecimalSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) {
                updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue()));
            }
        }
    });
    this.currencyComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent itemEvent) {
            //convert after currency change (not necessary, but useful)
            Currency oldCurrency = (Currency) itemEvent.getItem();
            Currency newCurrency = (Currency) itemEvent.getItemSelectable().getSelectedObjects()[0];
            double newAmount;
            try {
                newAmount = oldCurrency.getConverterTo(newCurrency).convert(getAmount());
            } catch (ConversionException ex) {
                try {
                    //if the exchange rate isn't set
                    AmountMoneyPanel.this.amountMoneyExchangeRateRetriever.retrieveExchangeRate(newCurrency);
                    AmountMoneyPanel.this.amountMoneyExchangeRateRetriever.retrieveExchangeRate(oldCurrency);
                    newAmount = oldCurrency.getConverterTo(newCurrency).convert(getAmount());
                } catch (AmountMoneyCurrencyStorageException amountMoneyCurrencyStorageException) {
                    throw new RuntimeException(amountMoneyCurrencyStorageException);
                }
            }
            AmountMoneyPanel.this.amountIntegerSpinner.setValue((int) newAmount);
            BigDecimal bd = new BigDecimal(newAmount * 100);
            bd = bd.setScale(0, //newScale
                    RoundingMode.HALF_UP //the rounding mode "taught in school"
            );
            AmountMoneyPanel.this.amountDecimalSpinner.setValue(bd.intValue() % 100);
            //notify registered update listeners
            for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) {
                updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue()));
            }
        }
    });
    this.amountMoneyCurrencyStorage = amountMoneyCurrencyStorage;
    this.amountMoneyUsageStatisticsStorage = amountMoneyUsageStatisticsStorage;
    this.amountMoneyExchangeRateRetriever = amountMoneyExchangeRateRetriever;
}