Example usage for java.util Observer Observer

List of usage examples for java.util Observer Observer

Introduction

In this page you can find the example usage for java.util Observer Observer.

Prototype

Observer

Source Link

Usage

From source file:com.rapidminer.template.gui.RoleRequirementSelector.java

public RoleRequirementSelector(final TemplateController controller) {
    super(new BorderLayout());
    setBorder(border);//from   w ww  .jav  a 2s  .  c  om
    this.controller = controller;

    setBackground(Color.WHITE);
    updateRequirement();
    controller.getModel().addObserver(new Observer() {

        @Override
        public void update(Observable o, Object arg) {
            if (TemplateState.OBSERVER_EVENT_TEMPLATE.equals(arg)) {
                updateRequirement();
                updateComponents();
            } else if (TemplateState.OBSERVER_EVENT_ROLES.equals(arg)) {
                assignSelectionToCombo();
                updateComponents();
                attributeCombo.repaint();
            } else if (TemplateState.OBSERVER_EVENT_INPUT.equals(arg)) {
                updateAttributes();
            }
        }
    });

    AutoCompleteDecorator.decorate(attributeCombo);
    AutoCompleteDecorator.decorate(positiveClassCombo);

    attributeCombo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (areValuesAdjusting) {
                return;
            }
            assignRoles();
        }
    });
    positiveClassCombo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (areValuesAdjusting) {
                return;
            }
            assignRoles();
        }
    });

    helpLabel.setHorizontalAlignment(SwingConstants.CENTER);
    add(helpLabel, BorderLayout.PAGE_START);

    chartPanel = new ChartPanel(null, 250, 250, 100, 100, 360, 360, true, false, false, false, false, false);
    chartPanel.setMinimumDrawWidth(0);
    chartPanel.setMaximumDrawWidth(Integer.MAX_VALUE);
    chartPanel.setMinimumDrawHeight(0);
    chartPanel.setMaximumDrawHeight(Integer.MAX_VALUE);
    attributeCombo.setPreferredSize(new Dimension(100, 30));
    attributeCombo.setMaximumSize(new Dimension(150, 30));
    add(chartPanel, BorderLayout.CENTER);

    JComponent comboPanel = new JPanel();
    comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.PAGE_AXIS));
    JComponent comboPanelAtt = new JPanel();
    comboPanelAtt.setBackground(Color.WHITE);
    comboPanelAtt.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    JComponent comboPanelClass = new JPanel();
    comboPanelClass.setBackground(Color.WHITE);
    comboPanelClass.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    positiveClassCombo.setPreferredSize(new Dimension(100, 30));
    positiveClassCombo.setMaximumSize(new Dimension(150, 30));
    positiveClassLabel.setLabelFor(positiveClassCombo);
    positiveClassLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
    positiveClassLabel.setToolTipText(positiveClassLabel.getText());
    positiveClassLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    columnLabel.setLabelFor(attributeCombo);
    columnLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
    columnLabel.setToolTipText(columnLabel.getText());
    columnLabel.setHorizontalAlignment(SwingConstants.RIGHT);

    comboPanelAtt.add(columnLabel);
    comboPanelAtt.add(attributeCombo);
    comboPanelClass.add(positiveClassLabel);
    comboPanelClass.add(positiveClassCombo);
    comboPanel.add(comboPanelAtt);
    comboPanel.add(comboPanelClass);

    add(comboPanel, BorderLayout.SOUTH);

    updateComponents();
}

From source file:org.sakaiproject.search.indexer.impl.ConcurrentSearchIndexBuilderWorkerImpl.java

public void init() {
    if (started && !runThreads) {
        log.warn("JVM Shutdown in progress, will not startup");
        return;/*ww  w.  j a  va  2s. c om*/
    }
    if (componentManager.hasBeenClosed()) {
        log.warn("Component manager Shutdown in progress, will not startup");
        return;
    }

    enabled = searchService.isEnabled()
            && "true".equals(serverConfigurationService.getString("search.indexqueue", "true"));

    started = true;
    runThreads = true;

    if (!enabled) {
        return;
    }

    eventTrackingService.addLocalObserver(new Observer() {

        public void update(Observable arg0, Object arg1) {
            lastEvent = System.currentTimeMillis();
        }

    });

}

From source file:me.drozdzynski.library.steppers.SteppersAdapter.java

@Override
public void onBindViewHolder(final SteppersViewHolder holder, int p) {
    final int position = holder.getAdapterPosition();
    final SteppersItem steppersItem = items.get(position);

    holder.setChecked(position < currentStep);
    if (holder.isChecked()) {
        holder.roundedView.setChecked(true);
    } else {//from   www. ja v  a 2 s.c o m
        holder.roundedView.setChecked(false);
        holder.roundedView.setText(position + 1 + "");
    }

    if (position == getItemCount() - 1)
        holder.lineBelowRoundedView.setVisibility(View.INVISIBLE);
    else
        holder.lineBelowRoundedView.setVisibility(View.VISIBLE);

    if (position == currentStep || holder.isChecked())
        holder.roundedView.setCircleAccentColor();
    else
        holder.roundedView.setCircleGrayColor();

    holder.textViewLabel.setText(steppersItem.getLabel());
    holder.textViewLabel.setTextColor(steppersItem.getLabelTextColor());

    if (steppersItem.getSubLabel().isEmpty()) {
        holder.textViewSubLabel.setVisibility(View.GONE);
    } else {

        holder.textViewSubLabel.setVisibility(View.VISIBLE);
        holder.textViewSubLabel.setText(steppersItem.getSubLabel());
        holder.textViewSubLabel.setTextColor(steppersItem.getSubLabelTextColor());

    }

    holder.linearLayoutContent
            .setVisibility(position == currentStep || position == beforeStep ? View.VISIBLE : View.GONE);

    holder.buttonContinue.setEnabled(steppersItem.isPositiveButtonEnable());
    steppersItem.addObserver(new Observer() {
        @Override
        public void update(Observable observable, Object data) {
            if (observable != null) {
                SteppersItem item = (SteppersItem) observable;
                holder.buttonContinue.setEnabled(item.isPositiveButtonEnable());
            }
        }
    });

    if (position == getItemCount() - 1) {

        if (config.getFinishStepText() != null)
            holder.buttonContinue.setText(config.getFinishStepText());
        else
            holder.buttonContinue.setText(context.getResources().getString(R.string.step_finish));

    } else {

        if (steppersItem.getNextBtnText() != null)
            holder.buttonContinue.setText(steppersItem.getNextBtnText());
        else if (config.getNextStepText() != null)
            holder.buttonContinue.setText(config.getNextStepText());
        else
            holder.buttonContinue.setText(context.getResources().getString(R.string.step_continue));
    }

    holder.buttonContinue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (position == getItemCount() - 1)
                config.getOnFinishAction().onFinish();
            else {
                if (steppersItem.getOnClickContinue() != null) {
                    steppersItem.getOnClickContinue().onClick();
                } else {
                    nextStep();
                }
            }
        }
    });

    if (config.getSkipStepText() != null)
        holder.buttonSkip.setText(config.getSkipStepText());

    if (steppersItem.isSkippable() && position < getItemCount() - 1) {
        holder.buttonSkip.setVisibility(View.VISIBLE);
        holder.buttonSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (steppersItem.getOnSkipStepAction() != null) {
                    steppersItem.getOnSkipStepAction().onSkipStep();
                }

                nextStep();
            }
        });
    } else {
        holder.buttonSkip.setVisibility(View.GONE);
    }

    if (config.getPreStepText() != null)
        holder.buttonCancel.setText(config.getPreStepText());

    if (steppersItem.isPreStepable() && position > 0) {
        holder.buttonCancel.setVisibility(View.VISIBLE);
        holder.buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (steppersItem.getOnCancelAction() != null)
                    steppersItem.getOnCancelAction().onCancel();

                if (config.getOnCancelAction() != null)
                    config.getOnCancelAction().onCancel();

                preStep();

            }
        });
    } else {
        holder.buttonCancel.setVisibility(View.GONE);
    }

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    //FrameLayout frameLayout = (FrameLayout) inflater.inflate(R.layout.frame_layout, holder.frameLayout, true);

    if (frameLayoutIds.get(position) == null)
        frameLayoutIds.put(position, findUnusedId(holder.itemView));

    //frameLayout.setId(frameLayoutIds.get(position));

    if (config.getFragmentManager() != null && steppersItem.getFragment() != null) {
        holder.frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
        holder.frameLayout.setTag(frameLayoutName());

        if (fragmentTransaction == null) {
            fragmentTransaction = fragmentManager.beginTransaction();
        }

        String name = makeFragmentName(steppersView.getId(), position);
        Fragment fragment = fragmentManager.findFragmentByTag(name);

        if (position == beforeStep) {
            if (fragment != null) {
                if (BuildConfig.DEBUG)
                    Log.v(TAG, "Removing item #" + position + ": f=" + fragment);
                fragmentTransaction.detach(fragment);
            }
        } else if (position == currentStep) {
            if (fragment != null) {
                if (BuildConfig.DEBUG)
                    Log.v(TAG,
                            "Attaching item #" + position + ": f=" + fragment + " d=" + fragment.isDetached());
                fragmentTransaction.attach(fragment);
            } else {
                fragment = steppersItem.getFragment();
                if (BuildConfig.DEBUG)
                    Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " n=" + name);
                fragmentTransaction.add(steppersView.getId(), fragment, name);

            }
        }

        if (fragmentTransaction != null) {
            fragmentTransaction.commitAllowingStateLoss();
            fragmentTransaction = null;
            fragmentManager.executePendingTransactions();
        }

        if (fragmentManager.findFragmentByTag(name) != null
                && fragmentManager.findFragmentByTag(name).getView() != null) {

            View fragmentView = fragmentManager.findFragmentByTag(name).getView();

            if (fragmentView.getParent() != null
                    && frameLayoutName() != ((View) fragmentView.getParent()).getTag()) {
                steppersView.removeViewInLayout(fragmentView);

                holder.frameLayout.removeAllViews();
                holder.frameLayout.addView(fragmentView);
            }
        }
    }

    if (beforeStep == position) {
        AnimationUtils.hide(holder.linearLayoutContent);
    }
    if (currentStep == position && !steppersItem.isDisplayed()) {
        steppersItem.setDisplayed(true);
    }
}

From source file:org.openpilot_nonag.uavtalk.Telemetry.java

/**
 * Constructor//from  www . j ava2 s  .c om
 */
public Telemetry(UAVTalk utalkIn, UAVObjectManager objMngr) {
    this.utalk = utalkIn;
    this.objMngr = objMngr;

    // Create a handler for object messages
    handler = new ObjectUpdateHandler();

    // Process all objects in the list
    List<List<UAVObject>> objs = objMngr.getObjects();
    ListIterator<List<UAVObject>> li = objs.listIterator();
    while (li.hasNext())
        registerObject(li.next().get(0)); // we only need to register one
    // instance per object type

    // Listen to new object creations
    objMngr.addNewInstanceObserver(new Observer() {
        @Override
        public void update(Observable observable, Object data) {
            newInstance((UAVObject) data);
        }
    });
    objMngr.addNewObjectObserver(new Observer() {
        @Override
        public void update(Observable observable, Object data) {
            newObject((UAVObject) data);
        }
    });

    // Listen to transaction completions from uavtalk
    utalk.setOnTransactionCompletedListener(utalk.new OnTransactionCompletedListener() {
        @Override
        void TransactionSucceeded(UAVObject data) {
            transactionCompleted(data, true);
        }

        @Override
        void TransactionFailed(UAVObject data) {
            if (DEBUG)
                logger.debug("TransactionFailed(" + data.getName() + ")");

            transactionCompleted(data, false);
        }

    });

    // Get GCS stats object
    gcsStatsObj = objMngr.getObject("GCSTelemetryStats");

    // Setup transaction timer
    transPending = false;
    // Setup and start the periodic timer
    timeToNextUpdateMs = 0;
    updateTimerSetPeriod(1000);
    // Setup and start the stats timer
    txErrors = 0;
    txRetries = 0;
}

From source file:ecosim.gui.SummaryPane.java

/**
 *  Private method to build the binning chart.
 *
 *  @return A ChartPanel containing the binning chart.
 *///from   w w w  . j a  v  a2  s.  co  m
private ChartPanel makeBinningChart() {
    final DefaultXYDataset binData = new DefaultXYDataset();
    final NumberFormat nf = NumberFormat.getInstance();
    final NumberAxis xAxis = new NumberAxis("Sequence identity criterion");
    nf.setMinimumFractionDigits(2);
    xAxis.setLowerBound(Binning.binLevels[0]);
    xAxis.setUpperBound(1.0D);
    xAxis.setTickUnit(new NumberTickUnit(0.05D, nf));
    LogAxis yAxis = new LogAxis("Number of bins");
    yAxis.setBase(2.0D);
    yAxis.setNumberFormatOverride(NumberFormat.getInstance());
    yAxis.setTickUnit(new NumberTickUnit(2.0D));
    yAxis.setMinorTickMarksVisible(true);
    yAxis.setAutoRangeMinimumSize(4.0D);
    yAxis.setSmallestValue(1.0D);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    for (int i = 0; i < seriesColors.length; i++) {
        renderer.setSeriesPaint(i, seriesColors[i]);
        renderer.setSeriesStroke(i, new BasicStroke(seriesStroke[i]));
    }
    XYPlot plot = new XYPlot(binData, xAxis, yAxis, renderer);
    JFreeChart binChart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    binChart.setPadding(new RectangleInsets(0.0D, 0.0D, 0.0D, 10.0D));
    LegendTitle legend = new LegendTitle(plot);
    legend.setMargin(new RectangleInsets(1.0D, 1.0D, 1.0D, 1.0D));
    legend.setFrame(new LineBorder());
    legend.setBackgroundPaint(Color.white);
    legend.setPosition(RectangleEdge.BOTTOM);
    plot.addAnnotation(new XYTitleAnnotation(0.001D, 0.999D, legend, RectangleAnchor.TOP_LEFT));
    final ChartPanel pane = new ChartPanel(binChart, false, true, true, false, false);
    // Watch for changes to the Summary object.
    summary.addObserver(new Observer() {
        public void update(Observable o, Object obj) {
            Summary s = (Summary) obj;
            ParameterEstimate estimate = s.getEstimate();
            ArrayList<BinLevel> bins = s.getBins();
            if (bins.size() > 0) {
                double[][] values = new double[2][bins.size()];
                Double low = 1.0d;
                for (int i = 0; i < bins.size(); i++) {
                    BinLevel bin = bins.get(i);
                    values[0][i] = bin.getCrit();
                    values[1][i] = bin.getLevel();
                    if (values[0][i] < low)
                        low = values[0][i];
                }
                binData.addSeries("sequences", values);
                xAxis.setLowerBound(low);
                if (low > 0.95d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.005D, nf));
                } else if (low > 0.90d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.010D, nf));
                } else if (low > 0.80d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.025D, nf));
                }
                if (estimate != null) {
                    double[][] omega = new double[2][bins.size()];
                    double[][] sigma = new double[2][bins.size()];
                    double[] omegaLine = estimate.getOmega();
                    double[] sigmaLine = estimate.getSigma();
                    for (int i = 0; i < bins.size(); i++) {
                        double crit = 1.0D - values[0][i];
                        double snp = s.getLength() * crit;
                        omega[0][i] = values[0][i];
                        sigma[0][i] = values[0][i];
                        omega[1][i] = Math.pow(2.0D, snp * omegaLine[0] + omegaLine[1]);
                        sigma[1][i] = Math.pow(2.0D, snp * sigmaLine[0] + sigmaLine[1]);
                    }
                    if (-1.0D * omegaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("omega", omega);
                    }
                    if (-1.0D * sigmaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("sigma", sigma);
                    }
                }
                // Repaint the summary pane.
                pane.repaint();
            }
        }
    });
    return pane;
}

From source file:info.guardianproject.otr.app.im.app.ContactListActivity.java

private void initAccount() {

    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(ContentUris.withAppendedId(Imps.Account.CONTENT_URI, mAccountId), null, null, null,
            null);//from  w w w. j av  a 2 s .co  m
    if (c == null) {
        finish();
        return;
    }
    if (!c.moveToFirst()) {
        c.close();
        finish();
        return;
    }

    mProviderId = c.getLong(c.getColumnIndexOrThrow(Imps.Account.PROVIDER));
    mHandler = new MyHandler(this);

    String username = c.getString(c.getColumnIndexOrThrow(Imps.Account.USERNAME));

    c.close();

    // BrandingResources brandingRes = mApp.getBrandingResource(mProviderId);
    // setTitle(brandingRes.getString(BrandingResourceIDs.STRING_BUDDY_LIST_TITLE, username));
    setTitle(username);
    // getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON,
    //       brandingRes.getDrawable(BrandingResourceIDs.DRAWABLE_LOGO));

    mGlobalSettingMap = new Imps.ProviderSettings.QueryMap(getContentResolver(), true, null);

    mApp.callWhenServiceConnected(mHandler, new Runnable() {
        public void run() {
            if (!mDestroyed) {
                mApp.dismissNotifications(mProviderId);
                mConn = mApp.getConnection(mProviderId);
                if (mConn == null) {
                    clearConnectionStatus();
                    try {
                        mConn = mApp.createConnection(mProviderId, mAccountId);
                    } catch (RemoteException e) {
                        Log.e(ImApp.LOG_TAG, "The connection cannot be created");
                        finish();
                    }
                }
                //  mFilterView.mPresenceView.setConnection(mConn);
                mFilterView.setConnection(mConn);
                mContactListView.setConnection(mConn);
                mContactListView.setHideOfflineContacts(mGlobalSettingMap.getHideOfflineContacts());
            }
        }
    });

    mContextMenuHandler = new ContextMenuHandler();
    mContactListView.getListView().setOnCreateContextMenuListener(this);

    mGlobalSettingMap.addObserver(new Observer() {
        public void update(Observable observed, Object updateData) {
            if (!mDestroyed) {
                mContactListView.setHideOfflineContacts(mGlobalSettingMap.getHideOfflineContacts());
            }
        }
    });

    showFilterView();

}

From source file:ecosim.gui.SummaryPane.java

/**
 *  Private method to build the text pane.
 *
 *  @return A JLayeredPane containing the text pane.
 *//* w  w w.  j a  v a 2s  .c  o  m*/
private JLayeredPane makeTextPane() {
    final String ls = System.getProperty("line.separator");
    final String fmt = "Outgroup: %s" + ls + "Number: %,d" + ls + "Length: %,d" + ls + "Diversity: %.2f" + ls;

    final JLayeredPane pane = new JLayeredPane();
    final JTextArea summaryTextArea = new JTextArea(String.format(fmt, summary.getOutgroup(), summary.getNu(),
            summary.getLength(), summary.getDiversity()));
    summaryTextArea.setBackground(getBackground());
    pane.setBorder(BorderFactory.createTitledBorder("Sequences"));
    pane.setLayout(new FlowLayout(0));
    pane.add(summaryTextArea);
    // Watch for changes to the Summary object.
    summary.addObserver(new Observer() {
        public void update(Observable o, Object obj) {
            Summary s = (Summary) obj;
            ParameterEstimate estimate = s.getEstimate();
            summaryTextArea
                    .setText(String.format(fmt, s.getOutgroup(), s.getNu(), s.getLength(), s.getDiversity()));
            pane.repaint();
        }
    });
    return pane;
}

From source file:org.sakaiproject.search.component.service.impl.SearchIndexBuilderWorkerImpl.java

public void init() {
    if (started && !runThreads) {
        log.warn("JVM Shutdown in progress, will not startup");
        return;// w w  w . j  av  a  2  s  .co m
    }
    if (org.sakaiproject.component.cover.ComponentManager.hasBeenClosed()) {
        log.warn("Component manager Shutdown in progress, will not startup");
        return;
    }
    started = true;
    runThreads = true;

    enabled = "true".equals(serverConfigurationService.getString("search.enable", "false"));

    enabled = enabled && serverConfigurationService.getBoolean("search.indexbuild", true);

    try {
        if (searchIndexBuilder == null) {
            log.error("Search Index Worker needs SearchIndexBuilder ");
        }
        if (searchService == null) {
            log.error("Search Index Worker needs SearchService ");
        }
        if (searchIndexBuilderWorkerDao == null) {
            log.error("Search Index Worker needs SearchIndexBuilderWorkerDao ");
        }
        if (eventTrackingService == null) {
            log.error("Search Index Worker needs EventTrackingService ");
        }
        if (entityManager == null) {
            log.error("Search Index Worker needs EntityManager ");
        }
        if (userDirectoryService == null) {
            log.error("Search Index Worker needs UserDirectortyService ");
        }
        if (sessionManager == null) {
            log.error("Search Index Worker needs SessionManager ");
        }
        log.debug("init start");
        indexBuilderThread = new Thread[numThreads];
        for (int i = 0; i < indexBuilderThread.length; i++) {
            indexBuilderThread[i] = new Thread(this);
            indexBuilderThread[i].setName("SearchBuilder_" + String.valueOf(i));
            indexBuilderThread[i].start();
        }

        eventTrackingService.addLocalObserver(new Observer() {

            public void update(Observable arg0, Object arg1) {
                lastEvent = System.currentTimeMillis();
            }

        });

        searchIndexBuilder.addIndexQueueListener(new IndexQueueListener() {

            public void added(String name) {
                checkRunning();
            }

        });

        /*
         * Capture shutdown
         */
        Runtime.getRuntime().addShutdownHook(new Thread() {
            /*
             * (non-Javadoc)
             * 
             * @see java.lang.Thread#run()
             */
            @Override
            public void run() {
                runThreads = false;
            }
        });

    } catch (Throwable t) {
        log.error("Failed to init ", t);
    }
}

From source file:ecosim.gui.SummaryPane.java

/**
 *  Private method to build the table pane.
 *
 *  @return A JLayeredPane containing the table pane.
 *///from w  w w .ja v  a  2  s  .c  om
private JLayeredPane makeTablePane() {
    String[] columnNames = { "", "Estimate", "Hillclimbing", "Low", "High" };
    Integer[] columnWidths = { 250, 60, 60, 60, 60 };
    Object[][] rowData = { { "Number of putative ecotypes (npop)", null, null, null, null },
            { "Rate of ecotype formation (omega)", null, null, null, null },
            { "Rate of periodic selection (sigma)", null, null, null, null } };
    final JLayeredPane pane = new JLayeredPane();
    final JTable table = new JTable(rowData, columnNames) {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    final JTableHeader header = table.getTableHeader();
    pane.setLayout(new BorderLayout());
    header.setReorderingAllowed(false);
    TableColumnModel cm = table.getColumnModel();
    for (int i = 0; i < columnWidths.length; i++) {
        TableColumn column = cm.getColumn(i);
        column.setMinWidth(columnWidths[i]);
        if (i == 0) {
            column.setCellRenderer(new DefaultTableCellRenderer() {
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                            row, column);
                    cell.setBackground(header.getBackground());
                    cell.setForeground(header.getForeground());
                    return cell;
                }
            });
        }
    }
    pane.add(table.getTableHeader(), "North");
    pane.add(table, "Center");
    // Watch for changes to the Summary object.
    summary.addObserver(new Observer() {
        public void update(Observable o, Object obj) {
            Summary s = (Summary) obj;
            ParameterEstimate estimate = s.getEstimate();
            ParameterSet hillclimbing = s.getHillclimbing();
            ParameterSet[] ci = s.getConfidenceInterval();
            if (estimate != null) {
                ParameterSet e = estimate.getResult();
                table.setValueAt(e.getNpop(), 0, 1);
                table.setValueAt(String.format("%.4f", e.getOmega()), 1, 1);
                table.setValueAt(String.format("%.4f", e.getSigma()), 2, 1);
            }
            if (hillclimbing != null) {
                table.setValueAt(hillclimbing.getNpop(), 0, 2);
                table.setValueAt(String.format("%.4f", hillclimbing.getOmega()), 1, 2);
                table.setValueAt(String.format("%.4f", hillclimbing.getSigma()), 2, 2);
            }
            if (ci[0].getNpop() != null) {
                table.setValueAt(ci[0].getNpop(), 0, 3);
                table.setValueAt(ci[1].getNpop(), 0, 4);
            }
            if (ci[1].getOmega() != null) {
                table.setValueAt(String.format("%.4f", ci[0].getOmega()), 1, 3);

                String fmt = "%.4f";
                if (ci[1].getOmega() > 10.0D) {
                    fmt = "%.1f";
                } else if (ci[1].getOmega() > 1.0D) {
                    fmt = "%.2f";
                }
                table.setValueAt(String.format(fmt, ci[1].getOmega()), 1, 4);
            }
            if (ci[1].getSigma() != null) {
                table.setValueAt(String.format("%.4f", ci[0].getSigma()), 2, 3);
                if (ci[1].getSigma() > 100.0D - MasterVariables.EPSILON) {
                    table.setValueAt("100", 2, 4);
                } else {
                    String fmt = "%.4f";
                    if (ci[1].getSigma() > 10.0D) {
                        fmt = "%.1f";
                    } else if (ci[1].getSigma() > 1.0D) {
                        fmt = "%.2f";
                    }
                    table.setValueAt(String.format(fmt, ci[1].getSigma()), 2, 4);
                }
            }
            pane.repaint();
        }
    });
    return pane;
}

From source file:org.talend.osgi.hook.OsgiLoaderTest.java

@Test
public void CheckFindingExistingJarUsingFindEntriesDoesNotTriggerMissingJarObservable()
        throws IOException, BundleException {
    final Boolean[] observerCalled = new Boolean[1];
    observerCalled[0] = false;//  www .  ja v  a 2  s.  c o  m
    Observer observer = new Observer() {

        @Override
        public void update(Observable o, Object arg) {
            if (arg != null && arg instanceof JarMissingEvent) {
                JarMissingEvent jarMissingEvent = (JarMissingEvent) arg;
                String jarName = jarMissingEvent.getJarName();
                if (jarName.equals(EXISTING_JAR_NAME)) {
                    observerCalled[0] = true;
                } else {
                    throw new RuntimeException(
                            "Missing jar observer did not receive the expected jar name:" + jarName + "!=" //$NON-NLS-1$
                                    + EXISTING_JAR_NAME);
                }
            } else {// notification is not expected so thrown an exception for the test to fail
                throw new RuntimeException("Missing jar observer did not receive the proper event :" + arg);
            }
        }
    };

    setupMissingJarLoadingObserver(observer);

    Bundle fragmentBundle = osgiBundle.getBundleContext().installBundle(FRAGMENT_WITH_LIB_FOLDER_URL);
    Bundle bundle = osgiBundle.getBundleContext().installBundle(BUNDLE_NO_LIB_FOLDER_URL);
    try {
        bundle.start();// I am not sure to understand why we need to start this bundle.
        // check finding of existing jar in fragment
        assertNotNull(bundle);
        FileLocator.find(bundle, new Path("lib/any-existing.jar"), null); //$NON-NLS-1$ 
        assertFalse("Observer should never be called", observerCalled[0]); //$NON-NLS-1$
    } finally {
        fragmentBundle.uninstall();
        bundle.uninstall();
        unsetupMissingJarLoadingObserver(observer);
    }
    bundle = Platform.getBundle(BUNDLE_NO_LIB);
    assertNull(bundle);
    fragmentBundle = Platform.getBundle(FRAGMENT_WITH_LIB);
    assertNull(fragmentBundle);
}