Search in sources :

Example 41 with Timer

use of javax.swing.Timer in project WorldPainter by Captain-Chaos.

the class ProgressComponent method start.

public void start() {
    if ("true".equalsIgnoreCase(System.getProperty("org.pepsoft.worldpainter.devMode"))) {
        stats = new ArrayList<>();
    }
    jButton1.setEnabled(cancelable);
    jProgressBar1.setIndeterminate(true);
    thread = new Thread(task.getName()) {

        @Override
        public void run() {
            try {
                result = task.execute(ProgressComponent.this);
                done();
            } catch (Throwable t) {
                exceptionThrown(t);
            }
        }
    };
    thread.start();
    start = System.currentTimeMillis();
    timer = new Timer(1000, this);
    timer.start();
}
Also used : Timer(javax.swing.Timer) AwtUtils.doOnEventThread(org.pepsoft.util.AwtUtils.doOnEventThread)

Example 42 with Timer

use of javax.swing.Timer in project zencash-swing-wallet-ui by ZencashOfficial.

the class MessagingPanel method sendMessage.

// String textToSend - if null, taken from the text area
// MessagingIdentity remoteIdentity - if null selection is taken
private void sendMessage(String textToSend, MessagingIdentity remoteIdentity) throws IOException, WalletCallException, InterruptedException {
    boolean sendAnonymously = this.sendAnonymously.isSelected();
    boolean sendReturnAddress = false;
    boolean updateMessagingIdentityJustBeforeSend = false;
    // Make sure contacts are available
    if (this.contactList.getNumberOfContacts() <= 0) {
        JOptionPane.showMessageDialog(this.parentFrame, "You have no messaging contacts in your contact list. To use messaging\n" + "you need to add at least one contact. You can add a contact by importing\n" + "their messaging identity using the menu item Messaging >> Import contact \n" + "identity.", "No messaging contacts available...", JOptionPane.ERROR_MESSAGE);
        return;
    }
    if ((remoteIdentity == null) && (this.contactList.getSelectedContact() == null)) {
        JOptionPane.showMessageDialog(this.parentFrame, "No messaging contact is selected in the contact list (on the right side of the UI).\n" + "In order to send an outgoing message you need to select a contact to send it to!", "No messaging contact is selected...", JOptionPane.ERROR_MESSAGE);
        return;
    }
    // Create a copy of the identity to make sure changes made temporarily to do get reflected until
    // storage s updated (such a change may be setting a Z address)
    final MessagingIdentity contactIdentity = (remoteIdentity != null) ? remoteIdentity.getCloneCopy() : this.contactList.getSelectedContact().getCloneCopy();
    // Make sure contact identity is full (not Unknown with no address to send to)
    if (Util.stringIsEmpty(contactIdentity.getSendreceiveaddress())) {
        String errroMessage = "The messaging contact selected: " + contactIdentity.getDiplayString() + "\n" + "seems to have no valid Z address for sending and receiving messages. \n";
        errroMessage += contactIdentity.isAnonymous() ? ("Since the contact is anonymous this means that the contact intentionally did\n" + "not send his Z address (for replies to be psosible). Message cannot be sent!") : ("Most likely the reason is that this contact's messaging identity is not \n" + "imported yet. Message cannot be sent!");
        JOptionPane.showMessageDialog(this.parentFrame, errroMessage, "Selected contact has to Z address to send message to!", JOptionPane.ERROR_MESSAGE);
        return;
    }
    // set for the recipient. Also ask the user if he wishes to send a return address.
    if (sendAnonymously) {
        // If also no thread ID is set yet...
        if (Util.stringIsEmpty(contactIdentity.getThreadID())) {
            if (!contactIdentity.isGroup()) {
                // Offer the user to send a return address
                int reply = JOptionPane.showConfirmDialog(this.parentFrame, "This is the first anomymous message you are sending to contact: \n" + contactIdentity.getDiplayString() + "\n" + "Do you wish to send him your send/receive messaging Z address so\n" + "that the contact may be able to answer your anonymous messages?", "Send return address?", JOptionPane.YES_NO_OPTION);
                if (reply == JOptionPane.YES_OPTION) {
                    sendReturnAddress = true;
                }
            }
            String threadID = UUID.randomUUID().toString();
            contactIdentity.setThreadID(threadID);
            // will have a thread ID set on the first arriving message!
            if (contactIdentity.isGroup() || (!Util.stringIsEmpty(contactIdentity.getSenderidaddress()))) {
                updateMessagingIdentityJustBeforeSend = true;
            } else {
                JOptionPane.showMessageDialog(this.parentFrame, "The contact: " + contactIdentity.getDiplayString() + "\n" + "has no message identification T address. It is not possible to \n" + "send a message!", "Contact has no message identification T address", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    } else {
        // Check to make sure a normal message is not being sent to an anonymous identity
        if (contactIdentity.isAnonymous()) {
            int reply = JOptionPane.showConfirmDialog(this.parentFrame, "The contact: " + contactIdentity.getDiplayString() + "\n" + "is anonymous. However you are about to send a message to him\n" + "that includes your sender identification T address. Are you sure\n" + "you wish to send him the message?", "Send message releavling your sender identification T address?", JOptionPane.YES_NO_OPTION);
            if (reply == JOptionPane.NO_OPTION) {
                return;
            }
        }
    }
    // Get the text to send as a message
    if (textToSend == null) {
        textToSend = this.writeMessageTextArea.getText();
    }
    if (textToSend.length() <= 0) {
        JOptionPane.showMessageDialog(this.parentFrame, "You have not written any text for a message to be sent. Please write some text\n" + "in the message text field...", "Message text is empty", JOptionPane.ERROR_MESSAGE);
        return;
    }
    // Make sure there is not another send operation going on - at this time
    if ((this.operationStatusTimer != null) || (!this.sendButton.isEnabled())) {
        JOptionPane.showMessageDialog(this.parentFrame, "There is currently another message sending operation under way.\n" + "Please wait until the operation is completed...", "Another message sending operation is under way!", JOptionPane.ERROR_MESSAGE);
        return;
    }
    // Disable sending controls, set status.
    this.sendButton.setEnabled(false);
    this.writeMessageTextArea.setEnabled(false);
    // Form the JSON message to be sent
    MessagingIdentity ownIdentity = this.messagingStorage.getOwnIdentity();
    MessagingOptions msgOptions = this.messagingStorage.getMessagingOptions();
    // Check to make sure the sending address has some funds!!!
    final double minimumBalance = msgOptions.getAmountToSend() + msgOptions.getTransactionFee();
    Double balance = null;
    Double unconfirmedBalance = null;
    Cursor oldCursor = this.parentFrame.getCursor();
    try {
        this.parentFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        balance = Double.valueOf(this.clientCaller.getBalanceForAddress(ownIdentity.getSendreceiveaddress()));
        unconfirmedBalance = Double.valueOf(this.clientCaller.getUnconfirmedBalanceForAddress(ownIdentity.getSendreceiveaddress()));
    } finally {
        this.parentFrame.setCursor(oldCursor);
    }
    if ((balance < minimumBalance) && (unconfirmedBalance < minimumBalance)) {
        Log.warning("Sending address has balance: {0} and unconfirmed balance: {1}", balance, unconfirmedBalance);
        JOptionPane.showMessageDialog(this.parentFrame, "The Z address used to send/receive messages has insufficient balance: \n" + ownIdentity.getSendreceiveaddress() + "\n" + "You will be redirected to the UI tab for sending ZEN to add some balance to it. You need only\n" + "a small amount e.g. typically 0.1 ZEN is suffucient to send 500 messages. After sending some\n" + "ZEN you need to wait for the transaciton to be confirmed (typically takes 2.5 minutes). It is\n" + "recommended to send ZEN to this Z address in two or more separate transactions (though one \n" + "transaction is sufficient).", "Z address to send/receive messages has insufficient balance...", JOptionPane.ERROR_MESSAGE);
        // Restore controls and move to the send cash tab etc.
        this.sendButton.setEnabled(true);
        this.writeMessageTextArea.setEnabled(true);
        sendCashPanel.prepareForSending(ownIdentity.getSendreceiveaddress());
        parentTabs.setSelectedIndex(3);
        return;
    }
    if ((balance < minimumBalance) && (unconfirmedBalance >= minimumBalance)) {
        Log.warning("Sending address has balance: {0} and unconfirmed balance: {1}", balance, unconfirmedBalance);
        JOptionPane.showMessageDialog(this.parentFrame, "The Z address used to send/receive messages has insufficient confirmed balance: \n" + ownIdentity.getSendreceiveaddress() + "\n" + "This usually means that the previous mesasaging transaction is not yet confirmed. You\n" + "need to wait for the transaciton to be confirmed (typically takes 2.5 minutes). This\n" + "problem may be avoided if you send ZEN to this Z address in two or more separate \n" + "transactions (when you supply the ZEN balance to be used for messaging).", "Z address to send/receive messages has insufficient confirmed balance...", JOptionPane.ERROR_MESSAGE);
        // Restore controls and move to the send cash tab etc.
        this.sendButton.setEnabled(true);
        this.writeMessageTextArea.setEnabled(true);
        return;
    }
    String memoString = null;
    JsonObject jsonInnerMessage = null;
    if (sendAnonymously) {
        // Form an anonymous message
        jsonInnerMessage = new JsonObject();
        jsonInnerMessage.set("ver", 1d);
        jsonInnerMessage.set("message", textToSend);
        jsonInnerMessage.set("threadid", contactIdentity.getThreadID());
        if (sendReturnAddress) {
            jsonInnerMessage.set("returnaddress", ownIdentity.getSendreceiveaddress());
        }
        JsonObject jsonOuterMessage = new JsonObject();
        jsonOuterMessage.set("zenmsg", jsonInnerMessage);
        memoString = jsonOuterMessage.toString();
    } else {
        // Sign a HEX encoded message ... to avoid possible UNICODE issues
        String signature = this.clientCaller.signMessage(ownIdentity.getSenderidaddress(), Util.encodeHexString(textToSend).toUpperCase());
        jsonInnerMessage = new JsonObject();
        jsonInnerMessage.set("ver", 1d);
        jsonInnerMessage.set("from", ownIdentity.getSenderidaddress());
        jsonInnerMessage.set("message", textToSend);
        jsonInnerMessage.set("sign", signature);
        JsonObject jsonOuterMessage = new JsonObject();
        jsonOuterMessage.set("zenmsg", jsonInnerMessage);
        memoString = jsonOuterMessage.toString();
    }
    final JsonObject jsonInnerMessageForFurtherUse = jsonInnerMessage;
    // Check the size of the message to be sent, error if it exceeds.
    final int maxSendingLength = 512;
    int overallSendingLength = memoString.getBytes("UTF-8").length;
    if (overallSendingLength > maxSendingLength) {
        Log.warning("Text length of exceeding message: {0}", textToSend.length());
        int difference = Math.abs(maxSendingLength - overallSendingLength);
        // We give exact size and advice on reduction...
        JOptionPane.showMessageDialog(this.parentFrame, "The text of the message you have written is too long to be sent. When\n" + "packaged as a memo it comes up to " + overallSendingLength + " bytes (maximum is " + maxSendingLength + " bytes)\n\n" + "Advice: try to reduce the message length by " + difference + " characters. The current\n" + "version of the ZEN messaging protocol supports approximately 330\n" + "characters per message (number is not exact - depends on character\n" + "encoding specifics).", "Message size exceeds currently supported limits...", JOptionPane.ERROR_MESSAGE);
        // Restore controls and exit
        this.sendButton.setEnabled(true);
        this.writeMessageTextArea.setEnabled(true);
        return;
    }
    if (updateMessagingIdentityJustBeforeSend) {
        if (!contactIdentity.isGroup()) {
            this.messagingStorage.updateContactIdentityForSenderIDAddress(contactIdentity.getSenderidaddress(), contactIdentity);
        } else {
            this.messagingStorage.updateGroupContactIdentityForSendReceiveAddress(contactIdentity.getSendreceiveaddress(), contactIdentity);
        }
    }
    // Finally send the message
    String tempOperationID = null;
    try {
        tempOperationID = this.clientCaller.sendMessage(ownIdentity.getSendreceiveaddress(), contactIdentity.getSendreceiveaddress(), msgOptions.getAmountToSend(), msgOptions.getTransactionFee(), memoString);
    } catch (WalletCallException wce) {
        Log.error("Wallet call error in sending message: ", wce);
        sendResultLabel.setText("<html><span style=\"font-size:0.8em;\">Send status: &nbsp;" + "<span style=\"color:red;font-weight:bold\">ERROR! </span></span></html>");
        JOptionPane.showMessageDialog(MessagingPanel.this.getRootPane().getParent(), "An error occurred upon sending message to contact: " + contactIdentity.getDiplayString() + ". \n" + "Error message is: " + wce.getMessage() + "\n" + "If the problem persists, you may need technical support :( ...\n", "Error in sending message", JOptionPane.ERROR_MESSAGE);
        sendMessageProgressBar.setValue(0);
        sendButton.setEnabled(true);
        writeMessageTextArea.setEnabled(true);
        // Exit prematurely
        return;
    }
    final String operationStatusID = tempOperationID;
    // Start a data gathering thread specific to the operation being executed - this is done is a separate
    // thread since the server responds more slowly during JoinSPlits and this blocks he GUI somewhat.
    final DataGatheringThread<Boolean> opFollowingThread = new DataGatheringThread<Boolean>(new DataGatheringThread.DataGatherer<Boolean>() {

        public Boolean gatherData() throws Exception {
            long start = System.currentTimeMillis();
            Boolean result = MessagingPanel.this.clientCaller.isSendingOperationComplete(operationStatusID);
            long end = System.currentTimeMillis();
            Log.info("Checking for messaging operation " + operationStatusID + " status done in " + (end - start) + "ms.");
            return result;
        }
    }, this.errorReporter, 2000, true);
    // Start a timer to update the progress of the operation
    this.operationStatusTimer = new Timer(2000, new ActionListener() {

        public int operationStatusCounter = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                Boolean opComplete = opFollowingThread.getLastData();
                if ((opComplete != null) && opComplete.booleanValue()) {
                    // End the special thread used to follow the operation
                    opFollowingThread.setSuspended(true);
                    boolean sendWasSuccessful = clientCaller.isCompletedOperationSuccessful(operationStatusID);
                    if (sendWasSuccessful) {
                        sendResultLabel.setText("<html><span style=\"font-size:0.8em;\">Send status: &nbsp;" + "<span style=\"color:green;font-weight:bold\">SUCCESSFUL</span></span></html>");
                    } else {
                        String errorMessage = clientCaller.getOperationFinalErrorMessage(operationStatusID);
                        sendResultLabel.setText("<html><span style=\"font-size:0.8em;\">Send status: &nbsp;" + "<span style=\"color:red;font-weight:bold\">ERROR! </span></span></html>");
                        JOptionPane.showMessageDialog(MessagingPanel.this.getRootPane().getParent(), "An error occurred when sending message to contact: " + contactIdentity.getDiplayString() + ". \n" + "Error message is: " + errorMessage + "\n\n" + "If the problem persists, you may need technical support :( ...\n", "Error in sending message", JOptionPane.ERROR_MESSAGE);
                    }
                    // Restore controls etc. final actions - reenable
                    sendMessageProgressBar.setValue(0);
                    operationStatusTimer.stop();
                    operationStatusTimer = null;
                    sendButton.setEnabled(true);
                    writeMessageTextArea.setEnabled(true);
                    // clear message from text area
                    writeMessageTextArea.setText("");
                    if (sendWasSuccessful) {
                        // Save message as outgoing
                        Message msg = new Message(jsonInnerMessageForFurtherUse);
                        msg.setTime(new Date());
                        msg.setDirection(DIRECTION_TYPE.SENT);
                        // TODO: We can get the transaction ID for outgoing messages but is is probably unnecessary
                        msg.setTransactionID("");
                        messagingStorage.writeNewSentMessageForContact(contactIdentity, msg);
                    }
                    // Update conversation text pane
                    displayMessagesForContact(contactIdentity);
                } else {
                    // Update the progress
                    sendResultLabel.setText("<html><span style=\"font-size:0.8em;\">Send status: &nbsp;" + "<span style=\"color:orange;font-weight:bold\">IN PROGRESS</span></span></html>");
                    operationStatusCounter += 2;
                    int progress = 0;
                    if (operationStatusCounter <= 100) {
                        progress = operationStatusCounter;
                    } else {
                        progress = 100 + (((operationStatusCounter - 100) * 6) / 10);
                    }
                    sendMessageProgressBar.setValue(progress);
                }
                MessagingPanel.this.repaint();
            } catch (Exception ex) {
                Log.error("Unexpected error in sending message: ", ex);
                MessagingPanel.this.errorReporter.reportError(ex);
            }
        }
    });
    // End timer operation
    operationStatusTimer.setInitialDelay(0);
    operationStatusTimer.start();
}
Also used : ActionEvent(java.awt.event.ActionEvent) JsonObject(com.eclipsesource.json.JsonObject) Cursor(java.awt.Cursor) URISyntaxException(java.net.URISyntaxException) WalletCallException(com.vaklinov.zcashui.ZCashClientCaller.WalletCallException) IOException(java.io.IOException) Date(java.util.Date) Timer(javax.swing.Timer) ActionListener(java.awt.event.ActionListener) DataGatheringThread(com.vaklinov.zcashui.DataGatheringThread) WalletCallException(com.vaklinov.zcashui.ZCashClientCaller.WalletCallException)

Example 43 with Timer

use of javax.swing.Timer in project org.alloytools.alloy by AlloyTools.

the class SimpleGUI method finishInit.

private void finishInit(String[] args, int width) {
    // Add the listeners
    try {
        wrap = true;
        frame.addWindowListener(doQuit());
    } finally {
        wrap = false;
    }
    frame.addComponentListener(this);
    // initialize the "allowed memory sizes" array
    // allowedMemorySizes = new
    // ArrayList<Integer>(initialAllowedMemorySizes);
    // int newmem = SubMemory.get();
    // if (!allowedMemorySizes.contains(newmem)) {
    // int newmemlen = allowedMemorySizes.size();
    // if (allowedMemorySizes.contains(768) || newmemlen==0)
    // SubMemory.set(768); // a nice default value
    // else
    // SubMemory.set(allowedMemorySizes.get(newmemlen-1));
    // }
    // Choose the appropriate font
    int fontSize = FontSize.get();
    String fontName = OurDialog.getProperFontName(FontName.get(), "Courier New", "Lucidia", "Courier", "Monospaced");
    FontName.set(fontName);
    // Copy required files from the JAR
    copyFromJAR();
    final String binary = alloyHome() + fs + "binary";
    // Create the menu bar
    JMenuBar bar = new JMenuBar();
    try {
        wrap = true;
        filemenu = menu(bar, "&File", doRefreshFile());
        editmenu = menu(bar, "&Edit", doRefreshEdit());
        runmenu = menu(bar, "E&xecute", doRefreshRun());
        optmenu = menu(bar, "&Options", doRefreshOption());
        windowmenu = menu(bar, "&Window", doRefreshWindow(false));
        windowmenu2 = menu(null, "&Window", doRefreshWindow(true));
        helpmenu = menu(bar, "&Help", null);
        if (!Util.onMac())
            menuItem(helpmenu, "About Alloy...", 'A', doAbout());
        menuItem(helpmenu, "Quick Guide", 'Q', doHelp());
        menuItem(helpmenu, "See the Copyright Notices...", 'L', doLicense());
    } finally {
        wrap = false;
    }
    // Pre-load the visualizer
    viz = new VizGUI(false, "", windowmenu2, enumerator, evaluator);
    viz.doSetFontSize(FontSize.get());
    // Create the toolbar
    try {
        wrap = true;
        toolbar = new JToolBar();
        toolbar.setFloatable(false);
        if (!Util.onMac())
            toolbar.setBackground(background);
        toolbar.add(OurUtil.button("New", "Starts a new blank model", "images/24_new.gif", doNew()));
        toolbar.add(OurUtil.button("Open", "Opens an existing model", "images/24_open.gif", doOpen()));
        toolbar.add(OurUtil.button("Reload", "Reload all the models from disk", "images/24_reload.gif", doReloadAll()));
        toolbar.add(OurUtil.button("Save", "Saves the current model", "images/24_save.gif", doSave()));
        toolbar.add(runbutton = OurUtil.button("Execute", "Executes the latest command", "images/24_execute.gif", doExecuteLatest()));
        toolbar.add(stopbutton = OurUtil.button("Stop", "Stops the current analysis", "images/24_execute_abort2.gif", doStop(2)));
        stopbutton.setVisible(false);
        toolbar.add(showbutton = OurUtil.button("Show", "Shows the latest instance", "images/24_graph.gif", doShowLatest()));
        toolbar.add(Box.createHorizontalGlue());
        toolbar.setBorder(new OurBorder(false, false, false, false));
    } finally {
        wrap = false;
    }
    // Choose the antiAlias setting
    OurAntiAlias.enableAntiAlias(AntiAlias.get());
    // Create the message area
    logpane = OurUtil.scrollpane(null);
    log = new SwingLogPanel(logpane, fontName, fontSize, background, Color.BLACK, new Color(.7f, .2f, .2f), this);
    // Create loggers for preference changes
    PreferencesDialog.logOnChange(log, A4Preferences.allUserPrefs().toArray(new Pref<?>[0]));
    // Create the text area
    text = new OurTabbedSyntaxWidget(fontName, fontSize, TabSize.get());
    text.listeners.add(this);
    text.enableSyntax(!SyntaxDisabled.get());
    // Add everything to the frame, then display the frame
    Container all = frame.getContentPane();
    all.setLayout(new BorderLayout());
    all.removeAll();
    JPanel lefthalf = new JPanel();
    lefthalf.setLayout(new BorderLayout());
    lefthalf.add(toolbar, BorderLayout.NORTH);
    text.addTo(lefthalf, BorderLayout.CENTER);
    splitpane = OurUtil.splitpane(JSplitPane.HORIZONTAL_SPLIT, lefthalf, logpane, width / 2);
    splitpane.setResizeWeight(0.5D);
    status = OurUtil.make(OurAntiAlias.label(" "), new Font(fontName, Font.PLAIN, fontSize), Color.BLACK, background);
    status.setBorder(new OurBorder(true, false, false, false));
    all.add(splitpane, BorderLayout.CENTER);
    all.add(status, BorderLayout.SOUTH);
    // Generate some informative log messages
    log.logBold("Alloy Analyzer " + Version.version() + " (build date: " + Version.buildDate() + " git " + Version.commit + ")\n\n");
    // If on Mac, then register an application listener
    try {
        wrap = true;
        if (Util.onMac()) {
            macUtil.registerApplicationListener(doShow(), doAbout(), doOpenFile(""), doQuit());
        }
    } catch (Throwable t) {
        System.out.println("Mac classes not there");
    } finally {
        wrap = false;
    }
    // Add the new JNI location to the java.library.path
    try {
        System.setProperty("java.library.path", binary);
        // The above line is actually useless on Sun JDK/JRE (see Sun's bug
        // ID 4280189)
        // The following 4 lines should work for Sun's JDK/JRE (though they
        // probably won't work for others)
        String[] newarray = new String[] { binary };
        java.lang.reflect.Field old = ClassLoader.class.getDeclaredField("usr_paths");
        old.setAccessible(true);
        old.set(null, newarray);
    } catch (Throwable ex) {
    }
    // Pre-load the preferences dialog
    prefDialog = new PreferencesDialog(log, binary);
    prefDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    try {
        wrap = true;
        prefDialog.addChangeListener(wrapToChangeListener(doOptRefreshFont()), FontName, FontSize, TabSize);
        prefDialog.addChangeListener(wrapToChangeListener(doOptAntiAlias()), AntiAlias);
        prefDialog.addChangeListener(wrapToChangeListener(doOptSyntaxHighlighting()), SyntaxDisabled);
        prefDialog.addChangeListener(wrapToChangeListener(doLookAndFeel()), LAF);
    } finally {
        wrap = false;
    }
    // If the temporary directory has become too big, then tell the user
    // they can "clear temporary directory".
    long space = computeTemporarySpaceUsed();
    if (space < 0 || space >= 20 * 1024768) {
        if (space < 0)
            log.logBold("Warning: Alloy4's temporary directory has exceeded 1024M.\n");
        else
            log.logBold("Warning: Alloy4's temporary directory now uses " + (space / 1024768) + "M.\n");
        log.log("To clear the temporary directory,\n" + "go to the File menu and click \"Clear Temporary Directory\"\n");
        log.logDivider();
        log.flush();
    }
    // Refreshes all the menu items
    doRefreshFile();
    OurUtil.enableAll(filemenu);
    doRefreshEdit();
    OurUtil.enableAll(editmenu);
    doRefreshRun();
    OurUtil.enableAll(runmenu);
    doRefreshOption();
    doRefreshWindow(false);
    OurUtil.enableAll(windowmenu);
    frame.setJMenuBar(bar);
    // Open the given file, if a filename is given in the command line
    for (String f : args) if (f.toLowerCase(Locale.US).endsWith(".als")) {
        File file = new File(f);
        if (file.exists() && file.isFile())
            doOpenFile(file.getPath());
    }
    // Update the title and status bar
    notifyChange();
    text.get().requestFocusInWindow();
    // Launch the welcome screen if needed
    if (!AlloyCore.isDebug() && Welcome.get()) {
        JCheckBox again = new JCheckBox("Show this message every time you start the Alloy Analyzer");
        again.setSelected(true);
        OurDialog.showmsg("Welcome", "Thank you for using the Alloy Analyzer " + Version.version(), " ", "Version 4 of the Alloy Analyzer is a complete rewrite,", "offering improvements in robustness, performance and usability.", "Models written in Alloy 3 will require some small alterations to run in Alloy 4.", " ", "Here are some quick tips:", " ", "* Function calls now use [ ] instead of ( )", "  For more details, please see http://alloy.mit.edu/alloy4/quickguide/", " ", "* The Execute button always executes the latest command.", "  To choose which command to execute, go to the Execute menu.", " ", "* The Alloy Analyzer comes with a variety of sample models.", "  To see them, go to the File menu and click Open Sample Models.", " ", again);
        doShow();
        Welcome.set(again.isSelected());
    }
    // Periodically ask the MailBug thread to see if there is a newer
    // version or not
    final long now = System.currentTimeMillis();
    final Timer t = new Timer(800, null);
    t.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n = MailBug.latestBuildNumber();
            // message may run into other user messages
            if (System.currentTimeMillis() - now >= 3000 || n <= Version.buildNumber()) {
                t.stop();
                return;
            }
            latestAlloyVersion = n;
            latestAlloyVersionName = MailBug.latestBuildName();
            log.logBold("An updated version of the Alloy Analyzer has been released.\n");
            log.log("Please visit alloy.mit.edu to download the latest version:\nVersion " + latestAlloyVersionName + "\n");
            log.logDivider();
            log.flush();
            t.stop();
        }
    });
    t.start();
}
Also used : JPanel(javax.swing.JPanel) ActionEvent(java.awt.event.ActionEvent) OurBorder(edu.mit.csail.sdg.alloy4.OurBorder) OurTabbedSyntaxWidget(edu.mit.csail.sdg.alloy4.OurTabbedSyntaxWidget) Font(java.awt.Font) Container(java.awt.Container) BorderLayout(java.awt.BorderLayout) BooleanPref(edu.mit.csail.sdg.alloy4.A4Preferences.BooleanPref) Pref(edu.mit.csail.sdg.alloy4.A4Preferences.Pref) StringPref(edu.mit.csail.sdg.alloy4.A4Preferences.StringPref) VerbosityPref(edu.mit.csail.sdg.alloy4.A4Preferences.VerbosityPref) ChoicePref(edu.mit.csail.sdg.alloy4.A4Preferences.ChoicePref) Color(java.awt.Color) JToolBar(javax.swing.JToolBar) JCheckBox(javax.swing.JCheckBox) VizGUI(edu.mit.csail.sdg.alloy4viz.VizGUI) Timer(javax.swing.Timer) ActionListener(java.awt.event.ActionListener) File(java.io.File) JMenuBar(javax.swing.JMenuBar)

Example 44 with Timer

use of javax.swing.Timer in project CodenameOne by codenameone.

the class BlockingAction method actionPerformed.

public final void actionPerformed(ActionEvent e) {
    RootPaneContainer r = (RootPaneContainer) ResourceEditorApp.getApplication().getMainFrame();
    glassPane = r.getGlassPane();
    final ImageIcon progress = new ImageIcon(getClass().getResource("/progress.gif"));
    final JComponent c = new JLabel(progress);
    c.addMouseListener(new MouseAdapter() {
    });
    c.addKeyListener(new KeyAdapter() {
    });
    r.setGlassPane(c);
    c.setVisible(true);
    t = new Timer(100, new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rotation += 10;
            if (rotation > 359) {
                rotation = 0;
            }
            c.repaint();
        }
    });
    t.setRepeats(true);
    t.start();
    start();
    new Thread(this).start();
}
Also used : ImageIcon(javax.swing.ImageIcon) Timer(javax.swing.Timer) ActionListener(java.awt.event.ActionListener) ActionEvent(java.awt.event.ActionEvent) KeyAdapter(java.awt.event.KeyAdapter) JComponent(javax.swing.JComponent) MouseAdapter(java.awt.event.MouseAdapter) RootPaneContainer(javax.swing.RootPaneContainer) JLabel(javax.swing.JLabel)

Example 45 with Timer

use of javax.swing.Timer in project CodenameOne by codenameone.

the class JCollapsiblePane method setAnimationParams.

/**
 * Sets the parameters controlling the animation
 *
 * @param params
 * @throws IllegalArgumentException
 *           if params is null
 */
private void setAnimationParams(AnimationParams params) {
    if (params == null) {
        throw new IllegalArgumentException("params can't be null");
    }
    if (animateTimer != null) {
        animateTimer.stop();
    }
    animationParams = params;
    animateTimer = new Timer(animationParams.waitTime, animator);
    animateTimer.setInitialDelay(0);
}
Also used : Timer(javax.swing.Timer)

Aggregations

Timer (javax.swing.Timer)130 ActionEvent (java.awt.event.ActionEvent)66 ActionListener (java.awt.event.ActionListener)62 IOException (java.io.IOException)12 JPanel (javax.swing.JPanel)12 JLabel (javax.swing.JLabel)11 BorderLayout (java.awt.BorderLayout)9 Dimension (java.awt.Dimension)9 Point (java.awt.Point)9 Color (java.awt.Color)8 JCheckBox (javax.swing.JCheckBox)8 MouseEvent (java.awt.event.MouseEvent)7 JFrame (javax.swing.JFrame)7 MouseAdapter (java.awt.event.MouseAdapter)6 Window (java.awt.Window)5 JButton (javax.swing.JButton)5 JDialog (javax.swing.JDialog)5 JScrollPane (javax.swing.JScrollPane)5 File (java.io.File)4 Date (java.util.Date)4