Example usage for java.beans PropertyChangeListener PropertyChangeListener

List of usage examples for java.beans PropertyChangeListener PropertyChangeListener

Introduction

In this page you can find the example usage for java.beans PropertyChangeListener PropertyChangeListener.

Prototype

PropertyChangeListener

Source Link

Usage

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

public void initComponentsManual() {
    attachmentPopupMenu = new JPopupMenu();
    JMenuItem viewAttach = new JMenuItem("View Attachment");
    viewAttach.setIcon(new ImageIcon(Frame.class.getResource("images/attach.png")));
    viewAttach.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            viewAttachment();/*from  ww  w  . j av a  2  s  . c om*/
        }
    });
    attachmentPopupMenu.add(viewAttach);

    JMenuItem exportAttach = new JMenuItem("Export Attachment");
    exportAttach.setIcon(new ImageIcon(Frame.class.getResource("images/report_disk.png")));
    exportAttach.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            exportAttachment();
        }
    });
    attachmentPopupMenu.add(exportAttach);

    pageSizeField.setDocument(new MirthFieldConstraints(3, false, false, true));
    pageNumberField.setDocument(new MirthFieldConstraints(7, false, false, true));

    advancedSearchPopup = new MessageBrowserAdvancedFilter(parent, this, "Advanced Search Filter", true, true);
    advancedSearchPopup.setVisible(false);

    LineBorder lineBorder = new LineBorder(new Color(0, 0, 0));
    TitledBorder titledBorder = new TitledBorder("Current Search");
    titledBorder.setBorder(lineBorder);

    lastSearchCriteriaPane.setBorder(titledBorder);
    lastSearchCriteriaPane.setBackground(Color.white);
    lastSearchCriteria.setBackground(Color.white);

    mirthDatePicker1.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent arg0) {
            allDayCheckBox.setEnabled(mirthDatePicker1.getDate() != null || mirthDatePicker2.getDate() != null);
            mirthTimePicker1.setEnabled(mirthDatePicker1.getDate() != null && !allDayCheckBox.isSelected());
        }
    });

    mirthDatePicker2.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent arg0) {
            allDayCheckBox.setEnabled(mirthDatePicker1.getDate() != null || mirthDatePicker2.getDate() != null);
            mirthTimePicker2.setEnabled(mirthDatePicker2.getDate() != null && !allDayCheckBox.isSelected());
        }
    });

    pageNumberField.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_ENTER && pageGoButton.isEnabled()) {
                jumpToPageNumber();
            }
        }
    });

    if (!Arrays.asList("postgres", "oracle", "mysql").contains(PlatformUI.SERVER_DATABASE)) {
        regexTextSearchCheckBox.setEnabled(false);
    }

    this.addAncestorListener(new AncestorListener() {

        @Override
        public void ancestorAdded(AncestorEvent event) {
        }

        @Override
        public void ancestorMoved(AncestorEvent event) {
        }

        @Override
        public void ancestorRemoved(AncestorEvent event) {
            // Stop waiting for message browser requests when the message browser 
            // is no longer being displayed
            parent.mirthClient.getServerConnection().abort(getAbortOperations());
            // Clear the message cache when leaving the message browser.
            parent.messageBrowser.clearCache();
            // Clear the table selection to prevent the selection listener from triggering multiple times while the model is being cleared
            deselectRows();
            // Clear the records in the table
            tableModel.clear();

            // Remove all columns
            for (TableColumn tableColumn : messageTreeTable.getColumns(true)) {
                messageTreeTable.removeColumn(tableColumn);
            }
        }

    });
}

From source file:org.openscience.jmol.app.Jmol.java

Jmol(Splash splash, JFrame frame, Jmol parent, int startupWidth, int startupHeight, String commandOptions,
        Point loc) {/*from  ww w .j av a 2s.c  o m*/
    super(true);
    this.frame = frame;
    this.startupWidth = startupWidth;
    this.startupHeight = startupHeight;
    numWindows++;

    try {
        say("history file is " + historyFile.getFile().getAbsolutePath());
    } catch (Exception e) {
    }

    frame.setTitle("Jmol");
    frame.getContentPane().setBackground(Color.lightGray);
    frame.getContentPane().setLayout(new BorderLayout());

    this.splash = splash;

    setBorder(BorderFactory.createEtchedBorder());
    setLayout(new BorderLayout());
    language = GT.getLanguage();

    status = (StatusBar) createStatusBar();
    say(GT._("Initializing 3D display..."));
    //
    display = new DisplayPanel(status, guimap, haveDisplay.booleanValue(), startupWidth, startupHeight);
    String adapter = System.getProperty("model");
    if (adapter == null || adapter.length() == 0)
        adapter = "smarter";
    if (adapter.equals("smarter")) {
        report("using Smarter Model Adapter");
        modelAdapter = new SmarterJmolAdapter();
    } else if (adapter.equals("cdk")) {
        report("the CDK Model Adapter is currently no longer supported. Check out http://bioclipse.net/. -- using Smarter");
        // modelAdapter = new CdkJmolAdapter(null);
        modelAdapter = new SmarterJmolAdapter();
    } else {
        report("unrecognized model adapter:" + adapter + " -- using Smarter");
        modelAdapter = new SmarterJmolAdapter();
    }
    appletContext = commandOptions;
    viewer = JmolViewer.allocateViewer(display, modelAdapter);
    viewer.setAppletContext("", null, null, commandOptions);

    if (display != null)
        display.setViewer(viewer);

    say(GT._("Initializing Preferences..."));
    preferencesDialog = new PreferencesDialog(frame, guimap, viewer);
    say(GT._("Initializing Recent Files..."));
    recentFiles = new RecentFilesDialog(frame);
    if (haveDisplay.booleanValue()) {
        say(GT._("Initializing Script Window..."));
        scriptWindow = new ScriptWindow(viewer, frame);
    }

    MyStatusListener myStatusListener;
    myStatusListener = new MyStatusListener();
    viewer.setJmolStatusListener(myStatusListener);

    say(GT._("Initializing Measurements..."));
    measurementTable = new MeasurementTable(viewer, frame);

    // Setup Plugin system
    // say(GT._("Loading plugins..."));
    // pluginManager = new CDKPluginManager(
    //     System.getProperty("user.home") + System.getProperty("file.separator")
    //     + ".jmol", new JmolEditBus(viewer)
    // );
    // pluginManager.loadPlugin("org.openscience.cdkplugin.dirbrowser.DirBrowserPlugin");
    // pluginManager.loadPlugin("org.openscience.cdkplugin.dirbrowser.DadmlBrowserPlugin");
    // pluginManager.loadPlugins(
    //     System.getProperty("user.home") + System.getProperty("file.separator")
    //     + ".jmol/plugins"
    // );
    // feature to allow for globally installed plugins
    // if (System.getProperty("plugin.dir") != null) {
    //     pluginManager.loadPlugins(System.getProperty("plugin.dir"));
    // }

    if (haveDisplay.booleanValue()) {

        // install the command table
        say(GT._("Building Command Hooks..."));
        commands = new Hashtable();
        if (display != null) {
            Action[] actions = getActions();
            for (int i = 0; i < actions.length; i++) {
                Action a = actions[i];
                commands.put(a.getValue(Action.NAME), a);
            }
        }

        menuItems = new Hashtable();
        say(GT._("Building Menubar..."));
        executeScriptAction = new ExecuteScriptAction();
        menubar = createMenubar();
        add("North", menubar);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add("North", createToolbar());

        JPanel ip = new JPanel();
        ip.setLayout(new BorderLayout());
        ip.add("Center", display);
        panel.add("Center", ip);
        add("Center", panel);
        add("South", status);

        say(GT._("Starting display..."));
        display.start();

        //say(GT._("Setting up File Choosers..."));

        /*      pcs.addPropertyChangeListener(chemFileProperty, exportAction);
         pcs.addPropertyChangeListener(chemFileProperty, povrayAction);
         pcs.addPropertyChangeListener(chemFileProperty, writeAction);
         pcs.addPropertyChangeListener(chemFileProperty, toWebAction);
         pcs.addPropertyChangeListener(chemFileProperty, printAction);
         pcs.addPropertyChangeListener(chemFileProperty,
         viewMeasurementTableAction);
         */

        if (menuFile != null) {
            menuStructure = viewer.getFileAsString(menuFile);
        }
        jmolpopup = JmolPopup.newJmolPopup(viewer, true, menuStructure, true);

    }

    // prevent new Jmol from covering old Jmol
    if (loc != null) {
        frame.setLocation(loc);
    } else if (parent != null) {
        Point location = parent.frame.getLocationOnScreen();
        int maxX = screenSize.width - 50;
        int maxY = screenSize.height - 50;

        location.x += 40;
        location.y += 40;
        if ((location.x > maxX) || (location.y > maxY)) {
            location.setLocation(0, 0);
        }
        frame.setLocation(location);
    }
    frame.getContentPane().add("Center", this);

    frame.addWindowListener(new Jmol.AppCloser());
    frame.pack();
    frame.setSize(startupWidth, startupHeight);
    ImageIcon jmolIcon = JmolResourceHandler.getIconX("icon");
    Image iconImage = jmolIcon.getImage();
    frame.setIconImage(iconImage);

    // Repositionning windows
    if (scriptWindow != null)
        historyFile.repositionWindow(SCRIPT_WINDOW_NAME, scriptWindow, 200, 100);

    say(GT._("Setting up Drag-and-Drop..."));
    FileDropper dropper = new FileDropper();
    final JFrame f = frame;
    dropper.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            //System.out.println("Drop triggered...");
            f.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            if (evt.getPropertyName().equals(FileDropper.FD_PROPERTY_FILENAME)) {
                final String filename = evt.getNewValue().toString();
                viewer.openFile(filename);
            } else if (evt.getPropertyName().equals(FileDropper.FD_PROPERTY_INLINE)) {
                final String inline = evt.getNewValue().toString();
                viewer.openStringInline(inline);
            }
            f.setCursor(Cursor.getDefaultCursor());
        }
    });

    this.setDropTarget(new DropTarget(this, dropper));
    this.setEnabled(true);

    say(GT._("Launching main frame..."));
}

From source file:com.microsoft.azure.hdinsight.spark.ui.SparkSubmissionContentPanel.java

private void addSparkClustersLineItem() {
    JLabel sparkClusterLabel = new JLabel("Spark clusters(Linux only)");
    sparkClusterLabel.setToolTipText(//  w  w  w.  j a va  2s  . c o m
            "The HDInsight Spark cluster you want to submit your application to. Only Linux cluster is supported.");
    GridBagConstraints c11 = new GridBagConstraints();
    c11.gridx = 0;
    c11.gridy = 0;
    c11.insets = new Insets(margin, margin, 0, margin);
    add(sparkClusterLabel, new GridBagConstraints(0, displayLayoutCurrentRow, 1, 1, 0, 0,
            GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(margin, margin, 0, margin), 0, 0));

    clustersListComboBox = new ComboboxWithBrowseButton();
    clustersListComboBox.setButtonIcon(StreamUtil.getImageResourceFile(REFRESH_BUTTON_PATH));
    clustersListComboBox.getButton().setToolTipText("Refresh");
    clustersListComboBox.getButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Cursor cursor = getCursor();
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            List<IClusterDetail> clusterDetails = ClusterManagerEx.getInstance()
                    .getClusterDetails(submitModel.getProject());
            setCursor(cursor);
            submitModel.setClusterComboBoxModel(clusterDetails);
        }
    });
    clustersListComboBox.getComboBox().setToolTipText(
            "The HDInsight Spark cluster you want to submit your application to. Only Linux cluster is supported.");
    clustersListComboBox.getComboBox().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName() == "model" && evt.getNewValue() instanceof DefaultComboBoxModel) {
                int size = ((DefaultComboBoxModel) evt.getNewValue()).getSize();
                setVisibleForFixedErrorMessageLabel(ErrorMessageLabelTag.ClusterName.ordinal(), size <= 0);
            }
        }
    });

    add(clustersListComboBox,
            new GridBagConstraints(1, displayLayoutCurrentRow, 0, 1, 1, 0, GridBagConstraints.WEST,
                    GridBagConstraints.HORIZONTAL, new Insets(margin, margin, 0, margin), 0, 0));

    errorMessageLabels[ErrorMessageLabelTag.ClusterName.ordinal()] = new JLabel(
            "Cluster Name Should not be null");
    errorMessageLabels[ErrorMessageLabelTag.ClusterName.ordinal()]
            .setForeground(DarkThemeManager.getInstance().getErrorMessageColor());

    clustersListComboBox.getComboBox().addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            setVisibleForFixedErrorMessageLabel(0, clustersListComboBox.getComboBox().getItemCount() == 0);
        }
    });

    add(errorMessageLabels[ErrorMessageLabelTag.ClusterName.ordinal()],
            new GridBagConstraints(1, ++displayLayoutCurrentRow, 0, 1, 1, 0, GridBagConstraints.WEST,
                    GridBagConstraints.NONE, new Insets(0, margin, 0, 0), 0, 0));
}

From source file:at.becast.youploader.gui.FrmMain.java

/**
 * /*from  w  ww  .  j a v  a2  s  .c  o m*/
 */
public void initComponents() {
    if (Main.debug)
        LOG.debug("init Components", FrmMain.class);

    int left = Integer.parseInt(Main.s.get("left", "0"));
    int top = Integer.parseInt(Main.s.get("top", "0"));
    int width = Integer.parseInt(Main.s.get("width", DEFAULT_WIDTH));
    int height = Integer.parseInt(Main.s.get("height", DEFAULT_HEIGHT));
    setBounds(left, top, width, height);
    TabbedPane = new JTabbedPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle(Main.APP_NAME + " " + Main.VERSION);
    setName("frmMain");
    //Main Tab Creation
    initMainTab();

    //Queue Tab creation
    initQueuetab();

    //Playlist Settings Tab creation
    initPlaylistSettingsTab();

    statusBar = new StatusBar();

    GroupLayout layout = new GroupLayout(getContentPane());
    layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
            .addComponent(statusBar, GroupLayout.DEFAULT_SIZE, 884, Short.MAX_VALUE)
            .addComponent(TabbedPane, GroupLayout.DEFAULT_SIZE, 884, Short.MAX_VALUE));
    layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,
            layout.createSequentialGroup()
                    .addComponent(TabbedPane, GroupLayout.PREFERRED_SIZE, 498, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED).addComponent(statusBar,
                            GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)));
    getContentPane().setLayout(layout);

    cmbCategory.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent arg0) {
            changeCategory();
        }
    });
    QueuePanel.revalidate();
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private void initParameters() {

    final PropertyChangeListener recomputeListener = new PropertyChangeListener() {
        @Override//from   w  w w.  java  2s.  c  o  m
        public void propertyChange(PropertyChangeEvent evt) {
            computeChartDataIfPossible();
        }
    };

    bindingContext.addPropertyChangeListener(RoiMaskSelector.PROPERTY_NAME_USE_ROI_MASK, recomputeListener);
    bindingContext.addPropertyChangeListener(RoiMaskSelector.PROPERTY_NAME_ROI_MASK, recomputeListener);
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_BOX_SIZE, recomputeListener);
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_DATA_FIELD, recomputeListener);

    final PropertyChangeListener computeLineDataListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            computeRegressionAndAcceptableDeviationData();
        }
    };
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_SHOW_ACCEPTABLE_DEVIATION, computeLineDataListener);
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_ACCEPTABLE_DEVIATION, computeLineDataListener);
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_SHOW_REGRESSION_LINE, computeLineDataListener);

    final PropertyChangeListener rangeLabelUpdateListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            final VectorDataNode pointDataSource = scatterPlotModel.pointDataSource;
            final AttributeDescriptor dataField = scatterPlotModel.dataField;
            if (dataField != null && pointDataSource != null) {
                final String dataFieldName = dataField.getLocalName();
                getPlot().getDomainAxis().setLabel(dataFieldName);
                xAxisRangeControl.setTitleSuffix(dataFieldName);
            } else {
                getPlot().getDomainAxis().setLabel("");
                xAxisRangeControl.setTitleSuffix("");
            }
        }
    };

    bindingContext.addPropertyChangeListener(PROPERTY_NAME_DATA_FIELD, rangeLabelUpdateListener);
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_POINT_DATA_SOURCE, rangeLabelUpdateListener);

    bindingContext.addPropertyChangeListener(PROPERTY_NAME_X_AXIS_LOG_SCALED, new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            updateScalingOfXAxis();
        }
    });
    bindingContext.addPropertyChangeListener(PROPERTY_NAME_Y_AXIS_LOG_SCALED, new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            updateScalingOfYAxis();
        }
    });

    xAxisRangeControl.getBindingContext().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            handleAxisRangeControlChanges(evt, xAxisRangeControl, getPlot().getDomainAxis(),
                    xAutoRangeAxisRange);
        }
    });
    yAxisRangeControl.getBindingContext().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            handleAxisRangeControlChanges(evt, yAxisRangeControl, getPlot().getRangeAxis(),
                    yAutoRangeAxisRange);
        }
    });

}

From source file:biz.wolschon.fileformats.gnucash.jwsdpimpl.GnucashAccountWritingImpl.java

/**
 * same as getBalance(new Date()).<br/>
 * ignores transactions after the current date+time<br/>
 * This implementation caches the result.<br/>
 * We assume that time does never move backwards
 * @see #getBalance(Date)//from ww w  . ja va2 s  . c o  m
 */
@Override
public FixedPointNumber getBalance() {

    if (myBalanceCached != null) {
        return myBalanceCached;
    }

    Collection<GnucashTransactionSplit> after = new LinkedList<GnucashTransactionSplit>();
    FixedPointNumber balance = getBalance(new Date(), after);

    if (after.isEmpty()) {
        myBalanceCached = balance;

        // add a listener to keep the cache up to date
        if (myBalanceCachedInvalidtor != null) {
            myBalanceCachedInvalidtor = new PropertyChangeListener() {
                private final Collection<GnucashTransactionSplit> splitsWeAreAddedTo = new HashSet<GnucashTransactionSplit>();

                public void propertyChange(final PropertyChangeEvent evt) {
                    myBalanceCached = null;

                    // we don't handle the case of removing an account
                    // because that happenes seldomly enough

                    if (evt.getPropertyName().equals("account")
                            && evt.getSource() instanceof GnucashWritableTransactionSplit) {
                        GnucashWritableTransactionSplit splitw = (GnucashWritableTransactionSplit) evt
                                .getSource();
                        if (splitw.getAccount() != GnucashAccountWritingImpl.this) {
                            splitw.removePropertyChangeListener("account", this);
                            splitw.removePropertyChangeListener("quantity", this);
                            splitw.getTransaction().removePropertyChangeListener("datePosted", this);
                            splitsWeAreAddedTo.remove(splitw);

                        }

                    }
                    if (evt.getPropertyName().equals("transactionSplits")) {
                        Collection<GnucashTransactionSplit> splits = (Collection<GnucashTransactionSplit>) evt
                                .getNewValue();
                        for (GnucashTransactionSplit split : splits) {
                            if (!(split instanceof GnucashWritableTransactionSplit)
                                    || splitsWeAreAddedTo.contains(split)) {
                                continue;
                            }
                            GnucashWritableTransactionSplit splitw = (GnucashWritableTransactionSplit) split;
                            splitw.addPropertyChangeListener("account", this);
                            splitw.addPropertyChangeListener("quantity", this);
                            splitw.getTransaction().addPropertyChangeListener("datePosted", this);
                            splitsWeAreAddedTo.add(splitw);
                        }
                    }
                }
            };
            addPropertyChangeListener("currencyID", myBalanceCachedInvalidtor);
            addPropertyChangeListener("currencyNameSpace", myBalanceCachedInvalidtor);
            addPropertyChangeListener("transactionSplits", myBalanceCachedInvalidtor);
        }
    }

    return balance;
}

From source file:org.esa.beam.visat.toolviews.stat.HistogramPanel.java

private JPanel createOptionsPanel() {
    final JLabel numBinsLabel = new JLabel("#Bins:");
    JTextField numBinsField = new JTextField(Integer.toString(NUM_BINS_DEFAULT));
    numBinsField.setPreferredSize(new Dimension(50, numBinsField.getPreferredSize().height));
    final JCheckBox histoLogCheck = new JCheckBox("Log10 scaled bins");

    histoLogCheck.addActionListener(configChangeListener);

    bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS)
            .setDescription("Set the number of bins in the histogram");
    bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS)
            .setValueRange(new ValueRange(2.0, 2048.0));
    bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setDefaultValue(NUM_BINS_DEFAULT);
    bindingContext.bind(PROPERTY_NAME_NUM_BINS, numBinsField);

    bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM)
            .setDescription("Use log-10 scaled values for computation of histogram");
    bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).setDefaultValue(false);
    bindingContext.bind(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, histoLogCheck);
    log10HistEnablement = bindingContext.bindEnabledState(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, true,
            new Enablement.Condition() {
                @Override/*from  w w  w . j  a v  a 2  s  .  c o m*/
                public boolean evaluate(BindingContext bindingContext) {
                    return getRaster() != null && getRaster().getStx().getMaximum() > 0;
                }
            });

    PropertyChangeListener logChangeListener = new AxisControlChangeListener();

    xAxisRangeControl.getBindingContext().addPropertyChangeListener(logChangeListener);
    xAxisRangeControl.getBindingContext().getPropertySet()
            .addProperty(bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM));
    xAxisRangeControl.getBindingContext().getPropertySet()
            .addProperty(bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOG_SCALED));
    xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_LOG_SCALED)
            .setDescription("Toggle whether to use a logarithmic x-axis");
    log10AxisEnablement = xAxisRangeControl.getBindingContext().bindEnabledState(PROPERTY_NAME_LOG_SCALED, true,
            new Enablement.Condition() {
                @Override
                public boolean evaluate(BindingContext bindingContext) {
                    HistogramPanelModel.HistogramConfig currentConfig = createHistogramConfig();
                    boolean hasStx = model.hasStx(currentConfig);
                    // log10 xAxis is enabled when current histogram exists and is NOT log10 scaled
                    return dataset != null && hasStx && !model.getStx(currentConfig).isLogHistogram();
                }
            });

    JPanel dataSourceOptionsPanel = GridBagUtils.createPanel();
    GridBagConstraints dataSourceOptionsConstraints = GridBagUtils
            .createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2");
    GridBagUtils.addToPanel(dataSourceOptionsPanel, new JLabel(" "), dataSourceOptionsConstraints,
            "gridwidth=2,gridy=0,gridx=0,weightx=0");
    GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsLabel, dataSourceOptionsConstraints,
            "insets.top=2,insets.left=4,gridwidth=1,gridy=1,gridx=0,weightx=1");
    GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsField, dataSourceOptionsConstraints,
            "insets.top=0,insets.left=0,insets.right=2,gridwidth=1,gridy=1,gridx=1");
    GridBagUtils.addToPanel(dataSourceOptionsPanel, histoLogCheck, dataSourceOptionsConstraints,
            "insets.right=0,gridwidth=2,gridy=2,gridx=0");

    xAxisRangeControl.getBindingContext().bind(PROPERTY_NAME_LOG_SCALED, new JCheckBox("Log10 scaled"));
    xAxisRangeControl.getBindingContext().addPropertyChangeListener(PROPERTY_NAME_LOG_SCALED,
            new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    ValueAxis oldAxis = chart.getXYPlot().getDomainAxis();
                    ValueAxis newAxis = StatisticChartStyling.updateScalingOfAxis((Boolean) evt.getNewValue(),
                            oldAxis, true);
                    chart.getXYPlot().setDomainAxis(newAxis);
                }
            });

    JPanel displayOptionsPanel = GridBagUtils.createPanel();
    GridBagConstraints displayOptionsConstraints = GridBagUtils
            .createConstraints("anchor=SOUTH,fill=HORIZONTAL,weightx=1");
    GridBagUtils.addToPanel(displayOptionsPanel, xAxisRangeControl.getPanel(), displayOptionsConstraints,
            "gridy=2");

    JPanel optionsPanel = GridBagUtils.createPanel();
    GridBagConstraints gbc = GridBagUtils
            .createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1");
    GridBagUtils.addToPanel(optionsPanel, dataSourceOptionsPanel, gbc, "gridy=0");
    GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=1,fill=VERTICAL,weighty=1");
    GridBagUtils.addToPanel(optionsPanel, displayOptionsPanel, gbc, "gridy=2,fill=HORIZONTAL,weighty=0");
    GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=3,fill=VERTICAL,weighty=1");
    GridBagUtils.addToPanel(optionsPanel,
            xAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_LOG_SCALED).getComponents()[0], gbc,
            "gridy=4");
    return optionsPanel;
}

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

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

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

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

    autoAdvanceOption.addActionListener(new ActionListener() {
        @Override//from   w w w . ja  v  a  2 s  . co  m
        public void actionPerformed(ActionEvent e) {
            updateMovementControls();
        }
    });

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

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

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

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

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

    fieldLayoutTable = fieldViewPanel.getFieldLayoutTable();

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

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

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

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

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

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

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

            //                GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false);

            fieldLayoutTable.repaint();
        }
    });

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

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

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.trial = trial;

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

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

    setContentPane(splitPane);

    updateMovementControls();
    pack();
}

From source file:uk.ac.diamond.scisoft.analysis.rcp.inspector.InspectionTab.java

@Override
public void setParameters(ILazyDataset data, List<AxisSelection> datasetAxisList,
        List<PlotAxisProperty> plotAxisList) {
    if (axesListener != null && daxes != null) {
        for (AxisSelection a : daxes) {
            a.removePropertyChangeListener(axesListener);
        }//  w  ww.j a  v a2s  . c om
    }
    super.setParameters(data, datasetAxisList, plotAxisList);
    if (daxes != null) {
        if (axesListener == null) {
            axesListener = new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    repopulateCombos(evt.getOldValue().toString(), evt.getNewValue().toString());
                }
            };
        }
        for (AxisSelection a : daxes) {
            a.addPropertyChangeListener(axesListener);
        }
    }

    if (combos != null)
        populateCombos();
}

From source file:com.vladsch.idea.multimarkdown.settings.MultiMarkdownSettingsPanel.java

public MultiMarkdownSettingsPanel() {
    clearCustomCssButton.addActionListener(new ActionListener() {
        @Override/*from w  ww .  ja v a  2s . co m*/
        public void actionPerformed(ActionEvent e) {
            textCustomCss.setText("");
        }
    });

    btnLoadDefault.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //String cssFileText = MultiMarkdownGlobalSettings.getInstance().getCssFileText(htmlThemeComboBox.getSelectedIndex());
            //String base64Css = Base64.encodeBase64URLSafeString(MultiMarkdownGlobalSettings.getInstance().getCssText().getBytes(Charset.forName("utf-8")));
            //String cssText = new String(Base64.decodeBase64(base64Css), Charset.forName("utf-8"));
            MultiMarkdownGlobalSettings settings = MultiMarkdownGlobalSettings.getInstance();
            textCustomCss.setText((useOldPreviewCheckBox.isSelected()
                    ? settings.getCssFileText(htmlThemeList.getSelectedIndex(), false)
                    : (includesColorsCheckBox.isSelected()
                            ? settings.getCssFileText(htmlThemeList.getSelectedIndex(), true)
                            : "")
                            + (includesLayoutCssCheckBox.isSelected() ? settings.getLayoutCssFileText() : "")
                            + (includesHljsCssCheckBox.isSelected() && useHighlightJsCheckBox.isSelected()
                                    ? settings.getHljsCssFileText(htmlThemeList.getSelectedIndex(), true)
                                    : "")));
        }
    });

    showHtmlTextCheckBox.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            showHtmlTextStateChanged();
        }
    });

    showHtmlTextCheckBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            showHtmlTextStateChanged();
        }
    });

    focusEditorButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textCustomCss.requestFocus();
        }
    });

    ItemListener itemListener1 = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            updateCustomCssControls();
        }
    };
    useCustomCssCheckBox.addItemListener(itemListener1);
    useHighlightJsCheckBox.addItemListener(itemListener1);

    textCustomCss.addDocumentListener(new DocumentAdapter() {
        @Override
        public void documentChanged(DocumentEvent e) {
            super.documentChanged(e);
            updateCustomCssControls();
        }
    });

    if (MultiMarkdownGlobalSettings.getInstance().fxPreviewFailedBuild.isFailedBuild()) {
        // set it and disable
        useOldPreviewCheckBox.setSelected(true);
        useOldPreviewCheckBox.setEnabled(false);
    }

    updateUseOldPreviewControls();
    ItemListener itemListener = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            updateUseOldPreviewControls();
        }
    };
    useOldPreviewCheckBox.addItemListener(itemListener);
    includesColorsCheckBox.addItemListener(itemListener);
    includesHljsCssCheckBox.addItemListener(itemListener);
    includesLayoutCssCheckBox.addItemListener(itemListener);

    if (htmlThemeComboBox instanceof ComboBox) {
        ((JComboBox) htmlThemeComboBox).addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (((JComboBox) htmlThemeComboBox).getSelectedIndex() != htmlThemeList.getSelectedIndex()) {
                    htmlThemeList.setSelectedIndex(((JComboBox) htmlThemeComboBox).getSelectedIndex());
                }
            }
        });

        htmlThemeList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (((JComboBox) htmlThemeComboBox).getSelectedIndex() != htmlThemeList.getSelectedIndex()) {
                    ((JComboBox) htmlThemeComboBox).setSelectedIndex(htmlThemeList.getSelectedIndex());
                }
            }
        });
    }

    //tippingJarEditorPane.setText("" +
    //        "<html>\n" +
    //        "  <head>\n" +
    //        "  <style>\n" +
    //        "     td { text-align: right; margin 0; padding 0 10px !important; }\n" +
    //        "     td.pic { width: 0; }\n" +
    //        "     p, table, tr, body, div { margin: 0 !important; padding: 0 !important; }\n" +
    //        "     table { /*border: 1px solid black;*/ width: 100%; float: right !important; }\n" +
    //        "  </style>\n" +
    //        "  </head>\n" +
    //        "  <body>\n" +
    //        "      <table>\n" +
    //        "        <tr>\n" +
    //        "          <td><b>If you like my work then please feel free to tip me.<br>I will view it as a show of appreciation and as a reward for my effort.</b></td>\n" +
    //        "          <td class=\"pic\"><a href=\"http://flattr.com/thing/4603764/vschidea-multimarkdown-on-GitHub\" title=\"Donate monthly to vsch using Flattr\"><img src=\"https://raw.githubusercontent.com/vsch/idea-multimarkdown/master/assets/images/flattr-tips.png\" border=\"0\" width=\"43\" height=\"53\" alt=\"Donate monthly to vsch using Flattr\" /></a></td>\n" +
    //        "          <td class=\"pic\"><a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NR7DAGTC8CXLU\" title=\"Donate once-off to vsch using Paypal\"><img src=\"https://raw.githubusercontent.com/vsch/idea-multimarkdown/master/assets/images/paypal-tips.png\" border=\"0\" width=\"43\" height=\"53\" alt=\"Donate once-off to vsch using Paypal\" /></a></td>\n" +
    //        "        </tr>\n" +
    //        "      </table>\n" +
    //        "  </body>\n" +
    //        "</html>\n" +
    //        "");

    String htmlText = "";
    try {
        htmlText = Resources.toString(getClass().getResource("/com/vladsch/idea/multimarkdown/NOTICE.html"),
                Charsets.UTF_8);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    MultiMarkdownPreviewEditor.setStyleSheet(noticesEditorPane);
    noticesEditorPane.setText(htmlText);

    //tippingJarEditorPane.addHyperlinkListener(listener);
    noticesEditorPane.addHyperlinkListener(SettingsPanelImpl.getHyperLinkListenerBrowseUrl());

    // we don't change these
    githubWikiLinksCheckBox.setEnabled(false);
    //githubWikiLinksLabel.setVisible(false);
}