List of usage examples for javax.swing Timer start
public void start()
Timer
, causing it to start sending action events to its listeners. From source file:net.rptools.maptool.client.ui.MapToolFrame.java
private Timer newChatTimer() { // Set up the Chat timer to listen for changes Timer tm = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent ae) { long currentTime = System.currentTimeMillis(); LinkedMap chatTimers = chatTyperTimers.getChatTypers(); List<String> removeThese = new ArrayList<String>(chatTimers.size()); @SuppressWarnings("unchecked") Set<String> playerTimers = chatTimers.keySet(); for (String player : playerTimers) { long playerTime = (Long) chatTimers.get(player); if (currentTime - playerTime >= (chatNotifyDuration * 1000)) { // set up a temp place and remove them after the loop removeThese.add(player); }/*from w w w. ja v a 2 s . c om*/ } for (String remove : removeThese) { chatTyperTimers.removeChatTyper(remove); } } }); tm.start(); return tm; }
From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java
protected void showNotificationPopup(String popupText, NotificationType type) { JPanel panel = new JPanel(new MigLayout("flowy")); panel.setBorder(BorderFactory.createLineBorder(Color.gray)); switch (type) { case WARNING: case WARNING_HTML: panel.setBackground(Color.yellow); break;/*from w w w .j a v a 2 s.co m*/ case ERROR: case ERROR_HTML: panel.setBackground(Color.orange); break; default: panel.setBackground(Color.cyan); } JLabel label = new JLabel(popupText); panel.add(label); Dimension labelSize = DesktopComponentsHelper.measureHtmlText(popupText); int x = frame.getX() + frame.getWidth() - (50 + labelSize.getSize().width); int y = frame.getY() + frame.getHeight() - (50 + labelSize.getSize().height); PopupFactory factory = PopupFactory.getSharedInstance(); final Popup popup = factory.getPopup(frame, panel, x, y); popup.show(); panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { popup.hide(); } }); PointerInfo pointerInfo = MouseInfo.getPointerInfo(); if (pointerInfo != null) { final Point location = pointerInfo.getLocation(); final Timer timer = new Timer(3000, null); timer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PointerInfo currentPointer = MouseInfo.getPointerInfo(); if (currentPointer == null) { timer.stop(); } else if (!currentPointer.getLocation().equals(location)) { popup.hide(); timer.stop(); } } }); timer.start(); } }
From source file:com.view.PortfolioManagerWindow.java
/** * Creates new form MainJFrame//from www. ja v a2 s . c om */ public PortfolioManagerWindow() { super(); //The following line is for the exit confirmation addWindowListener(new AreYouSure()); initComponents(); //START TIMER TO UPDATE ORDERS Timer timer = new Timer(5000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<SingleOrder> ordersDone = new ArrayList<>(); try { ordersDone = (ArrayList) CPMOrderMANIAC.updateOrders(); CPMEndOfDay.getEODData(); } catch (ExecutionException | InterruptedException | IOException | JSONException ex) { Logger.getLogger(PortfolioManagerWindow.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<SingleOrder> ordersPending = new ArrayList<>(); ArrayList<SingleOrder> ordersExecuted = new ArrayList<>(); if (null != ordersDone) { for (int i = 0; i < ordersDone.size(); i++) { String currStatus = ordersDone.get(i).getStatus(); if (currStatus.equals("Pending")) { ordersPending.add(ordersDone.get(i)); } if (currStatus.equals("Executed")) { ordersExecuted.add(ordersDone.get(i)); } } CPMOrderMANIAC.setPendings(ordersPending); CPMOrderMANIAC.setExecuted(ordersExecuted); PMOrderHistoryTable.setModel(CPMOrderMANIAC.getOHTableModel()); PMPendingOrdersTable.setModel(CPMOrderMANIAC.getPRTableModel()); //System.out.println("ABOUT TO SET MODEL OF EOD TABLE"); PMEODBoughtTable.setModel(CPMEndOfDay.getBuyTableModel()); PMEODSoldTable.setModel(CPMEndOfDay.getSellTableModel()); } else { System.out.println("ERROR UPDATING ORDERS"); } } }); timer.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { } timer.restart(); }
From source file:edu.mit.fss.examples.visual.gui.WorldWindVisualization.java
/** * Instantiates a new world wind visualization. * * @throws OrekitException the orekit exception *//*from w w w. j ava 2 s. c om*/ public WorldWindVisualization() throws OrekitException { logger.trace("Creating Orekit reference frames."); eme = ReferenceFrame.EME2000.getOrekitFrame(); itrf = ReferenceFrame.ITRF2008.getOrekitFrame(); // world wind frame is a fixed rotation from Earth inertial frame wwj = new Frame(itrf, new Transform(date, new Rotation(RotationOrder.ZXZ, 0, -Math.PI / 2, -Math.PI / 2)), "World Wind"); logger.trace("Creating World Window GL canvas and adding to panel."); wwd = new WorldWindowGLCanvas(); wwd.setModel(new BasicModel()); wwd.setPreferredSize(new Dimension(800, 600)); setLayout(new BorderLayout()); add(wwd, BorderLayout.CENTER); logger.trace("Creating and adding a renderable layer."); displayLayer = new RenderableLayer(); wwd.getModel().getLayers().add(displayLayer); logger.trace("Creating and adding a marker layer."); markerLayer = new MarkerLayer(); // allow markers above/below surface markerLayer.setOverrideMarkerElevation(false); wwd.getModel().getLayers().add(markerLayer); logger.trace("Creating and adding a sun renderable."); Vector3D position = sun.getPVCoordinates(date, wwj).getPosition(); sunShape = new Ellipsoid(wwd.getModel().getGlobe().computePositionFromPoint(convert(position)), 696000000., 696000000., 696000000.); ShapeAttributes sunAttributes = new BasicShapeAttributes(); sunAttributes.setInteriorMaterial(Material.YELLOW); sunAttributes.setInteriorOpacity(1.0); sunShape.setAttributes(sunAttributes); displayLayer.addRenderable(sunShape); logger.trace("Creating and adding a terminator."); LatLon antiSun = LatLon.fromRadians(-sunShape.getCenterPosition().getLatitude().radians, FastMath.PI + sunShape.getCenterPosition().getLongitude().radians); // set radius to a quarter Earth chord at the anti-sun position less // a small amount (100 m) to avoid graphics problems terminatorShape = new SurfaceCircle(antiSun, wwd.getModel().getGlobe().getRadiusAt(antiSun) * FastMath.PI / 2 - 100); ShapeAttributes nightAttributes = new BasicShapeAttributes(); nightAttributes.setInteriorMaterial(Material.BLACK); nightAttributes.setInteriorOpacity(0.5); terminatorShape.setAttributes(nightAttributes); displayLayer.addRenderable(terminatorShape); logger.trace("Creating and adding a panel for buttons."); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); buttonPanel.add(new JCheckBox(new AbstractAction("Inertial Frame") { private static final long serialVersionUID = 2287109397693524964L; @Override public void actionPerformed(ActionEvent e) { setInertialFrame(((JCheckBox) e.getSource()).isSelected()); } })); buttonPanel.add(new JButton(editOptionsAction)); add(buttonPanel, BorderLayout.SOUTH); logger.trace( "Creating a timer to rotate the sun renderable, " + "terminator surface circle, and stars layer."); Timer rotationTimer = new Timer(15, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { wwd.redraw(); try { BasicOrbitView wwdView; if (wwd.getView() instanceof BasicOrbitView) { wwdView = (BasicOrbitView) wwd.getView(); } else { return; } // rotate camera to simulate inertial frame if (wwd.getView().isAnimating() || !inertialFrame.get()) { // update eme datum rotationDatum = wwj.getTransformTo(eme, date) .transformPosition(convert(wwdView.getCenterPoint())); } else if (inertialFrame.get()) { Position newCenter = wwd.getModel().getGlobe().computePositionFromPoint( convert(eme.getTransformTo(wwj, date).transformPosition(rotationDatum))); // move to eme datum wwdView.setCenterPosition(newCenter); } // rotate stars layer for (Layer layer : wwd.getModel().getLayers()) { if (layer instanceof StarsLayer) { StarsLayer stars = (StarsLayer) layer; // find the EME coordinates of (0,0) Vector3D emeDatum = wwj.getTransformTo(eme, date).transformPosition(convert( wwd.getModel().getGlobe().computePointFromLocation(LatLon.fromDegrees(0, 0)))); // find the WWJ coordinates the equivalent point in ITRF Vector3D wwjDatum = itrf.getTransformTo(wwj, date).transformPosition(emeDatum); // set the longitude offset to the opposite of // the difference in longitude (i.e. from 0) stars.setLongitudeOffset(wwd.getModel().getGlobe() .computePositionFromPoint(convert(wwjDatum)).getLongitude().multiply(-1)); } } } catch (OrekitException ex) { logger.error(ex); } } }); // set initial 2-second delay for initialization rotationTimer.setInitialDelay(2000); rotationTimer.start(); }
From source file:neembuu.uploader.NeembuuUploader.java
/** * Creates new form NeembuuUploader/*from www . j a v a 2 s . co m*/ */ private NeembuuUploader() { //An error message will be printed. //Saying //java.lang.ClassNotFoundException: neembuu.release1.ui.mc.EmotionIconProviderImpl //please ignore it. mainComponent = new MainComponentImpl(this); //mainComponent = new NonUIMainComponent(); << When running in command line mode NULogger.getLogger().log(Level.INFO, "{0}: Starting up..", getClass().getName()); //Display the splashscreen until the NeembuuUploader is initialized //NeembuuUploaderSplashScreen.getInstance().setVisible(true); //Setup NeembuuUploaderProperties.. Create the file if it doesn't exist. NeembuuUploaderProperties.setUp(); //Initialize components initComponents(); initSorting(); initNotification(); setUpTrayIcon(); setUpFileChooser(); setUpHttpClient(); setupTabs(); //map each checkbox to its class in the hashmap variable //NULogger.getLogger().info("Setting checkbox operations"); //checkBoxOperations(); //Load previously saved state //loadSavedState(); //This 3rd party code is to enable Drag n Drop of files FileDrop fileDrop = new FileDrop(this, new FileDrop.Listener() { @Override public void filesDropped(java.io.File[] filesSelected) { //Ignore directories for (File file : filesSelected) { if (file.isFile()) { files.add(file); } } if (files.isEmpty()) { return; } //If one file is dropped, display its name.. If more than one dropped, display the number of files selected if (files.size() == 1) { inputFileTextField.setText(files.get(0) + ""); } else { inputFileTextField.setText(files.size() + " " + Translation.T().nfilesselected()); } NULogger.getLogger().info("Files Dropped"); } }); //Timer is used to periodically refresh the table so that the progress will appear smoothly. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { //Update every 1s Timer autoUpdate = new Timer(1000, new ActionListener() { //Check if the queue is locked. If not, repaint. @Override public void actionPerformed(ActionEvent e) { if (!QueueManager.getInstance().isQueueLocked()) { //Should not call firetablerowsupdated as it'll lose the selection of rows. // //So repaint is called. neembuuUploaderTable.repaint(); } } }); //Unnecessary.. but waits for 3 seconds within which other threads will get more juice and initialize faster.. //reduced from 10 to 3 as I moved to faster pc autoUpdate.setInitialDelay(3000); //Start the timer. autoUpdate.start(); NULogger.getLogger().info("Timer started.."); } }); //By now everything is loaded, so no need of splashscreen anymore,, dispose it. :) //NeembuuUploaderSplashScreen.getInstance().dispose(); NULogger.getLogger().info("Splash screen disposed.."); //Make the NeembuuUploader appear in center of screen. setLocationRelativeTo(null); selectFileButton.requestFocus(); setVisible(true); ThemeCheck.apply(this); selectFileButton.setBorder(BorderFactory.createEmptyBorder()); selectFileButton.setContentAreaFilled(false); selectFileButton.setToolTipText(Translation.T().selectFileButton()); selectFileButton.setFocusPainted(false); selectFolderButton.setBorder(BorderFactory.createEmptyBorder()); selectFolderButton.setContentAreaFilled(false); selectFolderButton.setToolTipText("Select Folder"); selectFolderButton.setFocusPainted(false); getLogButton.setBorder(BorderFactory.createEmptyBorder()); getLogButton.setContentAreaFilled(false); getLogButton.setToolTipText("Copy \"nu.log\" to the clipboard"); getLogButton.setFocusPainted(false); checkifLKSOn(); // starting a thread from a constructor is a bad way to do it // however, we dont have enough options here. }
From source file:com.view.TradeWindow.java
/** * Creates new form TradeWindow//w ww . j a v a 2s .com */ public TradeWindow() { super(); //The following line is for the exit confirmation addWindowListener(new AreYouSure()); initComponents(); //START TIMER TO UPDATE ORDERS Timer timer = new Timer(10000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<SingleOrder> ordersDone = new ArrayList<>(); ArrayList<SingleOrder> pendingOrders = new ArrayList<>(); ArrayList<Block> blockHistory = new ArrayList<>(); //MAKE PENDING ORDERS FROM PM UPDATE try { ordersDone = (ArrayList) CTraderOrderMANIAC.updateOrders(); } catch (InterruptedException | IOException | JSONException | ExecutionException ex) { Logger.getLogger(TradeWindow.class.getName()).log(Level.SEVERE, null, ex); } //MAKE BLOCK ORDER HISTORY UPDATE try { blockHistory = (ArrayList) CTraderOrderMANIAC.updateBlockOrderHistory(); } catch (InterruptedException | ExecutionException | IOException | JSONException ex) { Logger.getLogger(TradeWindow.class.getName()).log(Level.SEVERE, null, ex); } if (null != ordersDone) { for (SingleOrder o : ordersDone) { if (o.getStatus().equals("Pending")) { pendingOrders.add(o); } } int currentlyInPendings = CTraderOrderMANIAC.getPendings().size(); int updatedPendings = pendingOrders.size(); System.out.println( "Size of currentPend = " + currentlyInPendings + " and of updated: " + updatedPendings); CTraderOrderMANIAC.setPendings(pendingOrders); TraderIncomingRequestsTable.setModel(CTraderOrderMANIAC.getPRTableModel()); if (currentlyInPendings < updatedPendings) { showMessageDialog(null, "You have received new orders."); } } else { System.out.println("ERROR UPDATING ORDERS"); } if (null != blockHistory) { CTraderOrderMANIAC.setBlockHistory(blockHistory); TraderBlockHistoryTable.setModel(CTraderOrderMANIAC.getBlockHistoryTableModel()); } else { System.out.println("ERROR UPDATING BLOCKS"); } } }); timer.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } timer.restart(); }
From source file:net.sourceforge.pmd.cpd.GUI.java
private void go() { try {/* w ww . j av a2 s.c o m*/ File dirPath = new File(rootDirectoryField.getText()); if (!dirPath.exists()) { JOptionPane.showMessageDialog(frame, "Can't read from that root source directory", "Error", JOptionPane.ERROR_MESSAGE); return; } setProgressControls(true); Properties p = new Properties(); CPDConfiguration config = new CPDConfiguration(); config.setMinimumTileSize(Integer.parseInt(minimumLengthField.getText())); config.setEncoding(encodingField.getText()); config.setIgnoreIdentifiers(ignoreIdentifiersCheckbox.isSelected()); config.setIgnoreLiterals(ignoreLiteralsCheckbox.isSelected()); config.setIgnoreAnnotations(ignoreAnnotationsCheckbox.isSelected()); config.setIgnoreUsings(ignoreUsingsCheckbox.isSelected()); p.setProperty(LanguageFactory.EXTENSION, extensionField.getText()); LanguageConfig conf = languageConfigFor((String) languageBox.getSelectedItem()); Language language = conf.languageFor(p); config.setLanguage(language); CPDConfiguration.setSystemProperties(config); CPD cpd = new CPD(config); cpd.setCpdListener(this); tokenizingFilesBar.setMinimum(0); phaseLabel.setText(""); if (isLegalPath(dirPath.getPath(), conf)) { // should use the // language file filter // instead? cpd.add(dirPath); } else { if (recurseCheckbox.isSelected()) { cpd.addRecursively(dirPath); } else { cpd.addAllInDirectory(dirPath); } } Timer t = createTimer(); t.start(); cpd.go(); t.stop(); matches = new ArrayList<>(); for (Iterator<Match> i = cpd.getMatches(); i.hasNext();) { Match match = i.next(); setLabelFor(match); matches.add(match); } setListDataFrom(matches); String report = new SimpleRenderer().render(cpd.getMatches()); if (report.length() == 0) { JOptionPane.showMessageDialog(frame, "Done. Couldn't find any duplicates longer than " + minimumLengthField.getText() + " tokens"); } else { resultsTextArea.setText(report); } } catch (IOException t) { t.printStackTrace(); JOptionPane.showMessageDialog(frame, "Halted due to " + t.getClass().getName() + "; " + t.getMessage()); } catch (RuntimeException t) { t.printStackTrace(); JOptionPane.showMessageDialog(frame, "Halted due to " + t.getClass().getName() + "; " + t.getMessage()); } setProgressControls(false); }
From source file:org.apache.cayenne.modeler.util.LongRunningTask.java
/** * Configures the task to run in a separate thread, and immediately exits the method. * This method is allowed to be invoked from EventDispatchThread. */// www. j av a 2 s .c om public void start() { // prepare... setCanceled(false); this.finished = false; Thread task = new Thread(new Runnable() { public void run() { internalExecute(); } }); Timer progressDisplayTimer = new Timer(DEFAULT_MS_TO_DECIDE_TO_POPUP, new ActionListener() { public void actionPerformed(ActionEvent e) { showProgress(); } }); progressDisplayTimer.setRepeats(false); // start progressDisplayTimer.start(); task.start(); }
From source file:org.datacleaner.windows.AnalysisJobBuilderWindowImpl.java
private void updateLeftPanelVisibility(boolean show) { if (show) {//from w ww . j a va 2 s . c o m _leftPanel.setVisible(true); if (_leftPanel.isCollapsed()) { _leftPanel.setCollapsed(false); } } else { if (!_leftPanel.isCollapsed()) { _leftPanel.setCollapsed(true); } final Timer timer = new Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (_leftPanel.isCollapsed()) { _leftPanel.setVisible(false); } } }); timer.setRepeats(false); timer.start(); } }
From source file:org.datacleaner.windows.FileTransferProgressWindow.java
public void setFinished(String filename) { final int index = getIndex(filename); final String doneText = "Done!"; _infoLabels[index].setText(doneText); for (int i = 0; i < _infoLabels.length; i++) { if (!doneText.equals(_infoLabels[i].getText())) { // return if not all files have transfered return; }/*from w ww.j a va 2 s .c om*/ } final Timer timer = new Timer(1500, null); final ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FileTransferProgressWindow.this.dispose(); timer.stop(); } }; timer.addActionListener(listener); timer.start(); }