Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java

public void setupContent() {
    // there is a potential infinite loop below if this method
    // is called when the transgraph is not running, so we check
    // early to make sure it won't happen (see PDI-5009)
    if (!transGraph.isRunning() || transGraph.trans == null
            || !transGraph.trans.getTransMeta().isCapturingStepPerformanceSnapShots()) {
        showEmptyGraph();//from  w  ww.  ja  v a2 s. co m
        return; // TODO: display help text and rerty button
    }

    if (perfComposite.isDisposed()) {
        return;
    }

    // Remove anything on the perf composite, like an empty page message
    //
    for (Control control : perfComposite.getChildren()) {
        if (!control.isDisposed()) {
            control.dispose();
        }
    }

    emptyGraph = false;

    this.title = transGraph.trans.getTransMeta().getName();
    this.timeDifference = transGraph.trans.getTransMeta().getStepPerformanceCapturingDelay();
    this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();

    // Wait a second for the first data to pour in...
    // TODO: make this wait more elegant...
    //
    while (this.stepPerformanceSnapShots == null || stepPerformanceSnapShots.isEmpty()) {
        this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            // Ignore errors
        }
    }

    Set<String> stepsSet = stepPerformanceSnapShots.keySet();
    steps = stepsSet.toArray(new String[stepsSet.size()]);
    Arrays.sort(steps);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    Label dataListLabel = new Label(perfComposite, SWT.NONE);
    dataListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Metrics.Label"));
    spoon.props.setLook(dataListLabel);
    FormData fdDataListLabel = new FormData();

    fdDataListLabel.left = new FormAttachment(0, 0);
    fdDataListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataListLabel.top = new FormAttachment(0, Const.MARGIN + 5);
    dataListLabel.setLayoutData(fdDataListLabel);

    dataList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });

    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(dataListLabel, Const.MARGIN);
    fdDataList.bottom = new FormAttachment(40, Const.MARGIN);
    dataList.setLayoutData(fdDataList);

    Label stepsListLabel = new Label(perfComposite, SWT.NONE);
    stepsListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Steps.Label"));

    spoon.props.setLook(stepsListLabel);

    FormData fdStepsListLabel = new FormData();
    fdStepsListLabel.left = new FormAttachment(0, 0);
    fdStepsListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsListLabel.top = new FormAttachment(dataList, Const.MARGIN);
    stepsListLabel.setLayoutData(fdStepsListLabel);

    stepsList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(stepsListLabel, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(perfComposite, SWT.NONE);
    spoon.props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, Const.MARGIN);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    perfComposite.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    perfComposite.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null && !image.isDisposed()) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    final Timer timer = new Timer("TransPerfDelegate Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    // When the tab is closed, we remove the update timer
    //
    transPerfTab.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            timer.cancel();
        }
    });
}

From source file:ca.mcgill.hs.serv.LogFileUploaderService.java

/**
 * Starts the timer for reattempting file upload.
 *//*w  ww.  j  a  v  a2 s  .com*/
private void timerStart() {
    final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            uploadFiles();
        }
    };
    timer.schedule(task, DELAY);
}

From source file:com.diversityarrays.kdxplore.design.EntryFileImportDialog.java

public EntryFileImportDialog(Window owner, String title, File inputFile, Predicate<Role> entryHeadingFilter) {
    super(owner, title, ModalityType.APPLICATION_MODAL);

    this.entryHeadingFilter = entryHeadingFilter;
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    setGlassPane(backgroundRunner.getBlockingPane());

    useScrollBarOption.addActionListener(new ActionListener() {
        @Override//from w  w w . ja  va 2s  .  c om
        public void actionPerformed(ActionEvent e) {
            updateDataPreviewScrolling();
        }
    });

    headingRoleTableModel = createHeadingRoleTableModel();
    headingRoleTable = new HeadingRoleTable<>(headingRoleTableModel);
    headingTableScrollPane = new JScrollPane(headingRoleTable);
    GuiUtil.setVisibleRowCount(headingRoleTable, 10);

    JPanel roleAssignmentPanel = new JPanel(new BorderLayout());
    roleAssignmentPanel.add(headingTableScrollPane, BorderLayout.CENTER);

    headingRoleTable.setTransferHandler(flth);
    headingRoleTableModel.addChangeListener(headingRoleChangeListener);

    GuiUtil.setVisibleRowCount(dataPreviewTable, 10);
    dataPreviewTable.setTransferHandler(flth);
    dataPreviewScrollPane.setTransferHandler(flth);
    updateDataPreviewScrolling();

    dataPreviewScrollPane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            //                boolean useScrollBar = useScrollBarOption.isSelected();
            GuiUtil.initialiseTableColumnWidths(dataPreviewTable, true);
        }
    });

    Box top = Box.createHorizontalBox();
    top.add(new JLabel("# rows to preview: "));
    top.add(new JSpinner(previewRowCountSpinnerModel));
    top.add(Box.createHorizontalGlue());
    top.add(useScrollBarOption);

    JPanel dataPreviewPanel = new JPanel(new BorderLayout());
    dataPreviewPanel.add(GuiUtil.createLabelSeparator("Data Preview", top), BorderLayout.NORTH);
    dataPreviewPanel.add(dataPreviewScrollPane, BorderLayout.CENTER);

    headingWarning.setForeground(Color.RED);
    JLabel instructions = new JLabel("<HTML>Please assign a <i>Role</i> for each of the headings in your data"
            + "<br>You must specify one as the <i>Entry Name</i>."
            + "<br>Click on one of the <i>Role</i> cells and select from the dropdown"
            + "<br>To assign multiple headings, select the rows for which you wish"
            + "<br>to set the <i>Role</i> then right-click and choose from the dropdown.");
    instructions.setHorizontalAlignment(JLabel.CENTER);
    instructions.setBackground(Toast.PALE_YELLOW);

    JScrollPane instScroll = new JScrollPane(instructions);
    instScroll.setBackground(Toast.PALE_YELLOW);

    normalEntryNameField.getDocument()
            .addDocumentListener(new DocumentChangeListener((e) -> updateAcceptButton()));
    normalEntryNameField.setText(TrialDesignPreferences.getInstance().getNormalEntryTypeName());

    JPanel rolesPanel = new JPanel();
    GBH gbh = new GBH(rolesPanel, 2, 2, 0, 0);
    int y = 0;
    gbh.add(0, y, 1, 1, GBH.NONE, 0, 1, GBH.EAST, "Entry Type Name for non-Checks:");
    gbh.add(1, y, 1, 1, GBH.NONE, 1, 1, GBH.WEST, normalEntryNameField);
    gbh.add(2, y, 1, 1, GBH.NONE, 1, 1, GBH.WEST, saveForFuture);
    ++y;

    gbh.add(0, y, 3, 1, GBH.BOTH, 2, 1, GBH.CENTER, roleAssignmentPanel);
    ++y;

    JSplitPane headingsAndInstructions = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, rolesPanel, instScroll);

    JPanel headingPanel = new JPanel(new BorderLayout());
    headingPanel.add(GuiUtil.createLabelSeparator("Assign Roles for Headings"), BorderLayout.NORTH);
    headingPanel.add(headingsAndInstructions, BorderLayout.CENTER);
    headingPanel.add(headingWarning, BorderLayout.SOUTH);

    errorMessage.setEditable(false);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, dataPreviewPanel, headingPanel);
    splitPane.setResizeWeight(0.5);

    cardPanel.add(new JScrollPane(errorMessage), CARD_ERROR);
    cardPanel.add(splitPane, CARD_DATA);

    Box bot = Box.createHorizontalBox();
    bot.add(Box.createHorizontalGlue());
    bot.add(new JButton(cancelAction));
    bot.add(new JButton(acceptAction));
    acceptAction.setEnabled(false);

    Container cp = getContentPane();
    cp.add(cardPanel, BorderLayout.CENTER);
    cp.add(bot, BorderLayout.SOUTH);
    pack();

    sheetNamesComboBox.addActionListener(sheetNamesActionListener);

    Timer timer = new Timer(true);

    previewRowCountSpinnerModel.addChangeListener(new ChangeListener() {
        int nPreview;
        TimerTask timerTask = null;

        @Override
        public void stateChanged(ChangeEvent e) {
            nPreview = previewRowCountSpinnerModel.getNumber().intValue();

            if (timerTask == null) {
                timerTask = new TimerTask() {
                    int lastPreviewCount = nPreview;

                    @Override
                    public void run() {
                        if (lastPreviewCount == nPreview) {
                            System.err.println("Stable at " + lastPreviewCount);
                            // No change, do it now
                            cancel();
                            try {
                                updateDataPreview(lastPreviewCount);
                            } finally {
                                timerTask = null;
                            }
                        } else {
                            System.err.println("Changing from " + lastPreviewCount + " to " + nPreview);
                            lastPreviewCount = nPreview;
                        }
                    }
                };
                timer.scheduleAtFixedRate(timerTask, 500, 100);
            }
        }
    });

    sheetNamesComboBox.setVisible(false);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
            removeWindowListener(this);
            setFile(inputFile);
        }
    });
}

From source file:com.qspin.qtaste.ui.reporter.TestCaseReportTable.java

private void init() {
    final String tableLayoutProperty = interactive ? INTERACTIVE_TABLE_LAYOUT_PROPERTY
            : EXECUTION_TABLE_LAYOUT_PROPERTY;
    final String statusColumnProperty = tableLayoutProperty + ".status";
    final String testCaseColumnProperty = tableLayoutProperty + ".test_case";
    final String detailsColumnProperty = tableLayoutProperty + ".details";
    final String testbedColumnProperty = tableLayoutProperty + ".testbed";
    final String resultColumnProperty = tableLayoutProperty + ".result";

    tcModel = new DefaultTableModel(
            new Object[] { "Status", "Test Case", "Details", "Result", "Testbed", "Time", "." }, 0) {

        @Override/*  w  ww .jav a2  s .c o m*/
        public Class<?> getColumnClass(int columnIndex) {
            Class<?> dataType = super.getColumnClass(columnIndex);
            if (columnIndex == STATUS) {
                dataType = Icon.class;
            }
            return dataType;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int mColIndex) {
            return false;
        }
    };
    tcTable = new SortableJTable(new TableSorter(tcModel)) {

        public String getToolTipText(MouseEvent e) {
            Point p = e.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            if (colIndex < 0) {
                return null;
            }
            return convertObjectToToolTip(getValueAt(rowIndex, colIndex));
        }
    };
    tcTable.setColumnSelectionAllowed(false);

    int tcWidth = interactive ? 360 : 480;
    int tcStatusWidth = 40;
    int tcTestbedWidth = 100;
    int tcDetailsWidth = 360;
    int tcResultWidth = 150;
    GUIConfiguration guiConfiguration = GUIConfiguration.getInstance();
    List<?> list = guiConfiguration.configurationsAt(tableLayoutProperty);
    if (!list.isEmpty()) {
        try {
            tcWidth = guiConfiguration.getInt(testCaseColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
        }
        try {
            tcStatusWidth = guiConfiguration.getInt(statusColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
        }
        try {
            tcDetailsWidth = guiConfiguration.getInt(detailsColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
        }
        try {
            tcTestbedWidth = guiConfiguration.getInt(testbedColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
        }
        if (interactive) {
            try {
                tcResultWidth = guiConfiguration.getInt(resultColumnProperty);
            } catch (NoSuchElementException ex) {
                guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
            }
        }
    } else {
        tcWidth = interactive ? 360 : 480;

        guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
        guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
        guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
        guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
        if (interactive) {
            guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
        }
        try {
            guiConfiguration.save();
        } catch (ConfigurationException ex) {
            logger.error("Error while saving GUI configuration: " + ex.getMessage());
        }
    }

    TableColumnModel tcTableColumnModel = tcTable.getColumnModel();
    tcTableColumnModel.getColumn(TEST_CASE).setPreferredWidth(tcWidth);
    tcTableColumnModel.getColumn(STATUS).setPreferredWidth(tcStatusWidth);
    tcTableColumnModel.getColumn(STATUS).setMaxWidth(40);
    tcTableColumnModel.getColumn(DETAILS).setPreferredWidth(tcDetailsWidth);
    tcTableColumnModel.getColumn(TESTBED).setPreferredWidth(tcTestbedWidth);
    tcTableColumnModel.getColumn(EXEC_TIME).setPreferredWidth(70);
    tcTableColumnModel.getColumn(EXEC_TIME).setMinWidth(70);
    tcTableColumnModel.getColumn(EXEC_TIME).setMaxWidth(70);
    tcTableColumnModel.removeColumn(tcTableColumnModel.getColumn(TC));
    if (!interactive) {
        tcTable.getSelectionModel().addListSelectionListener(new TCResultsSelectionListeners());
    }
    tcTable.setName("tcTable");
    tcTableColumnModel.addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
        }

        public void columnRemoved(TableColumnModelEvent e) {
        }

        public void columnMoved(TableColumnModelEvent e) {
        }

        public void columnMarginChanged(ChangeEvent e) {
            try {
                // save the current layout
                int tcStatusWidth = tcTable.getColumnModel().getColumn(STATUS).getWidth();
                int tcWidth = tcTable.getColumnModel().getColumn(TEST_CASE).getWidth();
                int tcDetailsWidth = tcTable.getColumnModel().getColumn(DETAILS).getWidth();
                int tcResultWidth = tcTable.getColumnModel().getColumn(RESULT).getWidth();
                int tcTestbedWidth = tcTable.getColumnModel().getColumn(TESTBED).getWidth();
                // save it into the settings
                GUIConfiguration guiConfiguration = GUIConfiguration.getInstance();
                guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
                guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
                guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
                guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
                if (interactive) {
                    guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
                }
                guiConfiguration.save();
            } catch (ConfigurationException ex) {
                logger.error("Error while saving GUI configuration: " + ex.getMessage());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
        }
    });

    try {
        tcTable.setDefaultRenderer(Class.forName("java.lang.Object"), new TableCellRenderer());
    } catch (ClassNotFoundException ex) {
    }

    if (interactive) {
        displayTableForInteractiveMode();
    } else {
        displayTableForExecutionMode();
    }

    tcTable.addMouseListener(new TableMouseListener());

    // use timer for updating elapsed time every seconds
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            updateRunningTestCaseElapsedTime();
        }
    }, 1000, 1000);
}

From source file:burstcoin.jminer.core.round.Round.java

private void onRoundFinish(long blockNumber) {
    finishedBlockNumber = blockNumber;/* ww w.  j  a va  2 s  . c o m*/
    long elapsedRoundTime = new Date().getTime() - roundStartDate.getTime();
    triggerGarbageCollection();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            fireEvent(new RoundFinishedEvent(blockNumber, bestCommittedDeadline, elapsedRoundTime));
        }
    }, 250); // fire deferred

    triggerCleanup();
}

From source file:de.dtag.tlabs.cbclient.CBClient.java

public void start() {

    /*//from  ww w . j a va 2  s .  c  o m
     * Run the Polling stuff
     */
    pollingTimer = new Timer();
    pollingTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            performPolling();
        }
    }, 0L, pollingSeconds * 1000L);

}

From source file:burstcoin.jminer.core.round.Round.java

private void triggerCleanup() {
    TimerTask cleanupTask = new TimerTask() {
        @Override//from  ww w .j a v a  2 s .c  o m
        public void run() {
            if (!reader.cleanupReaderPool()) {
                triggerCleanup();
            }
        }
    };

    try {
        timer.schedule(cleanupTask, 1000);
    } catch (IllegalStateException e) {
        LOG.error("cleanup task already scheduled ...");
    }
}

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/* ww w  .  j av a2  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:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

private void startMonitor() {
    if (refreshTimer != null) {
        return;//from w w  w  . ja v a2 s . c o  m
    }
    refreshTimer = new Timer(true);
    refreshTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            while (true) {
                if (refreshTimer == null || !chartPanelVisible) {
                    break;
                }
                try {
                    refresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }, 1000, 500);
}

From source file:burstcoin.jminer.core.round.Round.java

private void triggerGarbageCollection() {
    timer.schedule(new TimerTask() {
        @Override//w  ww .j  a  v a 2 s  .c o m
        public void run() {
            LOG.debug("trigger garbage collection ... ");
            System.gc();
        }
    }, 1500);
}