Example usage for javax.swing SwingUtilities invokeLater

List of usage examples for javax.swing SwingUtilities invokeLater

Introduction

In this page you can find the example usage for javax.swing SwingUtilities invokeLater.

Prototype

public static void invokeLater(Runnable doRun) 

Source Link

Document

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread.

Usage

From source file:org.mongkie.ui.context.VisibilityContextPanel.java

@Override
public void unload() {
    SwingUtilities.invokeLater(new Runnable() {
        @Override/*from  w  w  w  . j a  v  a 2 s.c o m*/
        public void run() {
            if (currentDisplay != null) {
                Lookup.getDefault().lookup(FilterController.class).getModel(currentDisplay)
                        .removeModelListener(VisibilityContextPanel.this);
                currentDisplay.getGraph().removeGraphModelListener(VisibilityContextPanel.this);
                currentDisplay = null;
            }
            setVisible(false);
        }
    });
}

From source file:fxts.stations.transport.tradingapi.processors.ExecutionReportProcessor.java

private boolean doReject(ExecutionReport aExeRpt) {
    if (isDisconnect(aExeRpt)) {
        JOptionPane.showMessageDialog(TradeApp.getInst().getMainFrame(), aExeRpt.getFXCMErrorDetails(),
                "Problem with your order..please reconnect.", JOptionPane.ERROR_MESSAGE);
        TradingServerSession.getInstance().logout();
    } else {//from ww w .j  ava2s .com
        if (aExeRpt.getFXCMOrdStatus() != FXCMOrdStatusFactory.REQUOTED) {
            final String fxcmErrorDetails = aExeRpt.getFXCMErrorDetails();
            mLogger.debug("fxcmErrorDetails = " + fxcmErrorDetails);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Message m = new Message(new Date(), "FXCM", "Problem with your order..",
                            OraCodeFactory.toMessage(fxcmErrorDetails));
                    MessageDialog dialog = new MessageDialog(TradeApp.getInst().getMainFrame());
                    Liaison.getInstance().getTradeDesk().addMessage(m);
                    dialog.setMessage(m);
                    dialog.showModal();
                }
            });
            Liaison.getInstance().getTradeDesk().removeOrder(aExeRpt.getOrderID());
        }
    }
    return false;
}

From source file:cz.alej.michalik.totp.client.AddDialog.java

public AddDialog(final Properties prop) {
    System.out.println("Pridat novy zaznam");
    this.setTitle("Pidat");
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.setMinimumSize(new Dimension(600, 150));
    this.setLocationByPlatform(true);
    // Panel pro vytvoen okraj
    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(10, 10, 10, 10));
    panel.setLayout(new GridBagLayout());
    // Vlastnosti pro popisky
    GridBagConstraints label = new GridBagConstraints();
    label.insets = new Insets(2, 2, 2, 2);
    label.fill = GridBagConstraints.NONE;
    label.weightx = 1;//  ww  w.j  av a 2 s . c om
    // Vlastnosti pro pole
    GridBagConstraints field = new GridBagConstraints();
    field.insets = new Insets(2, 2, 2, 2);
    field.fill = GridBagConstraints.HORIZONTAL;
    field.weightx = 10;

    this.add(panel);

    // Nastavm ikonu okna
    try {
        String path = "/material-design-icons/content/drawable-xhdpi/ic_create_black_48dp.png";
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(App.class.getResource(path)));
    } catch (NullPointerException ex) {
        System.out.println("Icon not found");
    }

    // Pole pro pojmenovn zznamu
    // Ikona
    ImageIcon icon = null;
    try {
        String path = "/material-design-icons/editor/drawable-xhdpi/ic_format_color_text_black_18dp.png";
        icon = new ImageIcon(App.class.getResource(path));
    } catch (NullPointerException ex) {
        System.out.println("Icon not found");
    }
    // Pidn labelu s ikonou a nastavm velikost psma
    label.gridy = 0;
    field.gridy = 0;
    JLabel nameLabel = new JLabel("Nzev: ", icon, JLabel.CENTER);
    nameLabel.setFont(nameLabel.getFont().deriveFont(App.FONT_SIZE * 2 / 3));
    panel.add(nameLabel, label);
    // Pole pro jmno
    final JTextField name = new JTextField();
    name.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));
    name.setFont(name.getFont().deriveFont(App.FONT_SIZE * 2 / 3));
    panel.add(name, field);

    // Pole pro zadn sdlenho hesla
    // Ikona
    icon = null;
    try {
        String path = "/material-design-icons/hardware/drawable-xhdpi/ic_security_black_18dp.png";
        icon = new ImageIcon(App.class.getResource(path));
    } catch (NullPointerException ex) {
        System.out.println("Icon not found");
    }
    // Pidn labelu s ikonou
    label.gridy = 1;
    field.gridy = 1;
    JLabel secretLabel = new JLabel("Heslo: ", icon, JLabel.CENTER);
    secretLabel.setFont(secretLabel.getFont().deriveFont(App.FONT_SIZE * 2 / 3));
    panel.add(secretLabel, label);
    // Pole pro heslo
    final JTextField secret = new JTextField();
    secret.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));
    secret.setFont(secret.getFont().deriveFont(App.FONT_SIZE * 2 / 3));
    panel.add(secret, field);

    this.setVisible(true);

    // Akce pro odesln formule
    ActionListener submit = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            submit(prop, name, secret, false);
        }
    };

    // Pi stisku klvesy Enter odele formul
    name.addActionListener(submit);
    secret.addActionListener(submit);
    // Pi zmn pole pro heslo se vstup okamit zformtuje
    final Runnable sanitizer = new Runnable() {
        @Override
        public void run() {
            sanitize(secret);

        }
    };
    secret.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            SwingUtilities.invokeLater(sanitizer);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });

    // Pi zaven okna odele formul
    this.addWindowListener(new WindowListener() {

        @Override
        public void windowOpened(WindowEvent e) {
            // Ignorovat

        }

        @Override
        public void windowIconified(WindowEvent e) {
            // Ignorovat

        }

        @Override
        public void windowDeiconified(WindowEvent e) {
            // Ignorovat

        }

        @Override
        public void windowDeactivated(WindowEvent e) {
            // Ignorovat

        }

        @Override
        public void windowClosing(WindowEvent e) {
            // Odeslat
            submit(prop, name, secret, true);

        }

        @Override
        public void windowClosed(WindowEvent e) {
            // Ignorovat

        }

        @Override
        public void windowActivated(WindowEvent e) {
            // Ignorovat

        }
    });
}

From source file:forge.gui.CardDetailPanel.java

public final void setItem(final InventoryItemFromSet item) {
    nameCostLabel.setText(item.getName());
    typeLabel.setVisible(false);//from   w  ww.j a va 2 s.c om
    powerToughnessLabel.setVisible(false);
    idLabel.setText("");
    cdArea.setText(CardDetailUtil.getItemDescription(item));
    updateBorder(item instanceof IPaperCard ? Card.getCardForUi((IPaperCard) item).getView().getCurrentState()
            : null, true);

    final String set = item.getEdition();
    setInfoLabel.setText(set);
    setInfoLabel.setToolTipText("");
    if (StringUtils.isEmpty(set)) {
        setInfoLabel.setOpaque(false);
        setInfoLabel.setBorder(null);
    } else {
        final CardEdition edition = FModel.getMagicDb().getEditions().get(set);
        if (null != edition) {
            setInfoLabel.setToolTipText(edition.getName());
        }

        setInfoLabel.setOpaque(true);
        setInfoLabel.setBackground(Color.BLACK);
        setInfoLabel.setForeground(Color.WHITE);
        setInfoLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
    }

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            scrArea.getVerticalScrollBar().setValue(scrArea.getVerticalScrollBar().getMinimum());
        }
    });
}

From source file:com.github.rholder.gradle.intellij.DependencyViewer.java

public DependencyViewer(Project p, ToolWindow t) {
    super(true, true);
    this.project = p;
    this.toolWindow = t;
    this.splitter = new Splitter(false, 0.75f);
    this.information = new JTextArea();
    this.toolingLogger = initToolingLogger();

    this.dependencyCellRenderer = new DependencyCellRenderer();
    this.dependencyCellRenderer.omittedSelected = JBColor.MAGENTA;
    this.dependencyCellRenderer.omittedUnselected = JBColor.GRAY;
    this.dependencyCellRenderer.normalSelected = JBColor.foreground();
    this.dependencyCellRenderer.normalUnselected = JBColor.BLACK;
    this.information.setEditable(false);

    this.shouldPromptForCurrentProject = true;

    // TODO clean all of this up
    GradleService gradleService = ServiceManager.getService(project, GradleService.class);
    gradleService.addListener(new ViewActionListener() {
        @Override//w w w . j  a v a 2s .  c o m
        public void refresh() {
            if (shouldPromptForCurrentProject) {
                switch (useCurrentProjectBuild()) {
                case 0:
                    gradleBaseDir = project.getBasePath();
                    break;
                default: // do nothing, stay null
                }
                shouldPromptForCurrentProject = false;
            }

            if (gradleBaseDir == null) {
                promptForGradleBaseDir();
            }

            updateView(null, null);

            new SwingWorker<GradleNode, Void>() {
                protected GradleNode doInBackground() throws Exception {
                    try {
                        Map<String, GradleNode> dependencyMap = loadProjectDependenciesFromModel(gradleBaseDir,
                                toolingLogger);
                        GradleNode rootDependency = dependencyMap.get("root");

                        GradleNode target = dependencyCellRenderer.selectedGradleNode;
                        GradleNode selectedDependency;
                        if (target != null && target.group != null) {
                            selectedDependency = target;
                        } else {
                            selectedDependency = new GradleNode("No dependency selected");
                        }

                        updateView(rootDependency, selectedDependency);
                        return rootDependency;
                    } catch (Exception e) {
                        e.printStackTrace();
                        toolingLogger.log(ExceptionUtils.getFullStackTrace(e));
                        throw new RuntimeException(e);
                    }
                }
            }.execute();
        }

        @Override
        public void toggleShowReplaced() {
            dependencyCellRenderer.showReplaced = !dependencyCellRenderer.showReplaced;
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    splitter.repaint();
                    splitter.validate();
                }
            });
        }

        @Override
        public void reset() {
            gradleBaseDir = null;
            refresh();
        }
    });
    gradleService.refresh();

    setContent(splitter);
    final ActionManager actionManager = ActionManager.getInstance();
    ActionToolbar actionToolbar = actionManager.createActionToolbar("Gradle View Toolbar",
            (DefaultActionGroup) actionManager.getAction("GradleView.NavigatorActionsToolbar"), true);

    actionToolbar.setTargetComponent(splitter);
    setToolbar(actionToolbar.getComponent());
}

From source file:net.sf.profiler4j.console.Console.java

public void connect() {
    LongTask t = new LongTask() {
        public void executeInBackground() throws Exception {
            setTaskMessage("Establishing connection with remote JVM...");
            client.connect(project.getHostname(), project.getPort());
            setTaskMessage("Activating profiling rules...");
            client.applyRules(project.formatRules(), project.formatOptions(), new ProgressCallback() {
                private int max;

                public void operationStarted(int amount) {
                    max = amount;//from   w ww .j  ava 2s.  c o m
                }

                public void update(int value) {
                    setTaskProgress((value * 100) / max);
                    setTaskMessage("Activating profiling rules... (class " + value + " of " + max + ")");
                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    sendEvent(AppEventType.CONNECTED);
                    memoryPanelTimer.start();
                }
            });

        }
    };
    runInBackground(t);
}

From source file:edu.ku.brc.specify.tasks.SecurityAdminTask.java

/**
 * Enables the User to change password./*ww  w .  ja v a  2 s  .  com*/
 */
public static void changePassword(final boolean isStartingEmpty) {
    final ViewBasedDisplayDialog dlg = new ViewBasedDisplayDialog((Frame) UIRegistry.getTopWindow(),
            "SystemSetup", "ChangePassword", null, getResourceString(getKey("CHG_PWD_TITLE")), "OK", null, null,
            true, MultiView.HIDE_SAVE_BTN | MultiView.DONT_ADD_ALL_ALTVIEWS | MultiView.USE_ONLY_CREATION_MODE
                    | MultiView.IS_EDITTING);
    dlg.setWhichBtns(CustomDialog.OK_BTN | CustomDialog.CANCEL_BTN);

    dlg.setFormAdjuster(new FormPane.FormPaneAdjusterIFace() {
        @Override
        public void adjustForm(final FormViewObj fvo) {
            final ValPasswordField oldPwdVTF = fvo.getCompById("1");
            final ValPasswordField newPwdVTF = fvo.getCompById("2");
            final ValPasswordField verPwdVTF = fvo.getCompById("3");
            final PasswordStrengthUI pwdStrenthUI = fvo.getCompById("4");

            if (isStartingEmpty && pwdStrenthUI != null) {
                pwdStrenthUI.setDoPainting(true);
            }

            Institution institution = AppContextMgr.getInstance().getClassObject(Institution.class);
            int minPwdLen = (int) institution.getMinimumPwdLength();
            newPwdVTF.setMinLen(minPwdLen);
            verPwdVTF.setMinLen(minPwdLen);
            pwdStrenthUI.setMinPwdLen(minPwdLen);

            DocumentAdaptor da = new DocumentAdaptor() {
                @Override
                protected void changed(final DocumentEvent e) {
                    super.changed(e);

                    // Need to invoke later so the da gets to set the enabled state last.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {

                            String pwdStr = new String(newPwdVTF.getPassword());
                            String verStr = new String(verPwdVTF.getPassword());
                            boolean pwdOK = pwdStrenthUI.checkStrength(pwdStr) && pwdStr.equals(verStr)
                                    && newPwdVTF.getState() == UIValidatable.ErrorType.Valid;
                            dlg.getOkBtn().setEnabled(pwdOK);
                            pwdStrenthUI.repaint();
                        }
                    });
                }
            };

            oldPwdVTF.getDocument().addDocumentListener(da);
            verPwdVTF.getDocument().addDocumentListener(da);
            newPwdVTF.getDocument().addDocumentListener(da);
        }
    });

    Hashtable<String, String> valuesHash = new Hashtable<String, String>();
    dlg.setData(valuesHash);
    UIHelper.centerAndShow(dlg);

    if (!dlg.isCancelled()) {
        int pwdLen = 6;

        String oldPwd = valuesHash.get("OldPwd");
        String newPwd1 = valuesHash.get("NewPwd1");
        String newPwd2 = valuesHash.get("NewPwd2");

        if (newPwd1.equals(newPwd2)) {
            if (newPwd1.length() >= pwdLen) {
                SpecifyUser spUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
                //String      username  = spUser.getName();
                String spuOldPwd = spUser.getPassword();

                String newEncryptedPwd = null;
                String oldDecryptedPwd = Encryption.decrypt(spuOldPwd, oldPwd);
                if (oldDecryptedPwd != null && oldDecryptedPwd.equals(oldPwd)) {
                    newEncryptedPwd = Encryption.encrypt(newPwd2, newPwd2);
                    spUser.setPassword(newEncryptedPwd);
                    if (!DataModelObjBase.save(spUser)) {
                        UIRegistry.writeTimedSimpleGlassPaneMsg(getResourceString(getKey("PWD_ERR_SAVE")),
                                Color.RED);
                    }

                } else {
                    UIRegistry.writeTimedSimpleGlassPaneMsg(getResourceString(getKey("PWD_ERR_BAD")),
                            Color.RED);
                }

                if (newEncryptedPwd != null) {
                    Pair<String, String> masterPwd = UserAndMasterPasswordMgr.getInstance()
                            .getUserNamePasswordForDB();

                    String encryptedMasterUP = UserAndMasterPasswordMgr.encrypt(masterPwd.first,
                            masterPwd.second, newPwd2);
                    if (StringUtils.isNotEmpty(encryptedMasterUP)) {
                        AppPreferences.getLocalPrefs().put(
                                UserAndMasterPasswordMgr.getInstance().getMasterPrefPath(true),
                                encryptedMasterUP);
                        UIHelper.setTextToClipboard(encryptedMasterUP);
                        UIRegistry.showLocalizedMsg(JOptionPane.INFORMATION_MESSAGE, "INFORMATION",
                                "SPUSR_NEWPWD");

                    } else {
                        UIRegistry.writeTimedSimpleGlassPaneMsg(getResourceString(getKey("PWD_ERR_RTRV")),
                                Color.RED);
                    }

                } else {
                    UIRegistry.writeTimedSimpleGlassPaneMsg(getResourceString(getKey("PWD_ERR_BAD")),
                            Color.RED);
                }
            } else {
                UIRegistry.writeTimedSimpleGlassPaneMsg(getFormattedResStr(getKey("PWD_ERR_LEN"), pwdLen),
                        Color.RED);
            }
        } else {
            UIRegistry.writeTimedSimpleGlassPaneMsg(getResourceString(getKey("PWD_ERR_NOTSAME")), Color.RED);
        }
    }
}

From source file:ch.zhaw.iamp.rct.Controller.java

/**
 * Shows the {@link GrammarHelpWindow}. If there is no instance yet, one
 * will be created./*from  w w w. j av  a  2 s .co  m*/
 *
 * @param xPosition The x position at which the window may be put.
 * @param yPosition The y position at which the window may be put.
 */
public void showGrammarHelpWindow(final int xPosition, final int yPosition) {
    if (!isGrammarHelpWindowVisible()) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                grammarHelpWindow = new GrammarHelpWindow(grammarWindow, false);
                grammarHelpWindow.setLocation(xPosition, yPosition);
                Components.setIcons(grammarHelpWindow);
                grammarHelpWindow.setVisible(true);
            }
        });
    }
}

From source file:com.jbombardier.console.panels.MachineTelemetryPanel.java

/**
 * Create the panel./* w  ww .j  a  v  a 2s  .c  o  m*/
 */
public MachineTelemetryPanel() {
    setBorder(new TitledBorder(null, "Machine Telemetry", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    setLayout(new MigLayout("ins 0", "[grow,fill]0[grow,fill]0[grow,fill]0[grow,fill]", "[grow]0[grow]"));

    stackedBarCPU = ChartBuilder.startStackedBar().setTitle("CPU").setOrientation(PlotOrientation.HORIZONTAL)
            .setYAxisLabel("Percentage cpu").setYMaximum(100).setXAxisLabel("").setYAxisLabel("").toChart();
    stackedBarMemory = ChartBuilder.startStackedBar().setTitle("Memory")
            .setOrientation(PlotOrientation.HORIZONTAL).setYAxisLabel("MBytes").toChart();
    ioBarChart = ChartBuilder.startBar().setTitle("IO").setYAxisLabel("KBytes/sec")
            .setOrientation(PlotOrientation.HORIZONTAL).yAxisLock(1024).setVerticalXAxisLabels(true).toChart();

    // add(stackedBarCPU.getComponent(), "cell 0 0,grow");
    JPanel a = new JPanel();
    a.add(stackedBarCPU.getComponent());
    add(a, "cell 0 0,grow");
    a.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    // add(stackedBarMemory.getComponent(), "cell 1 0,grow");
    JPanel b = new JPanel();
    b.add(stackedBarMemory.getComponent());
    add(b, "cell 1 0,grow");
    b.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    // add(stackedBarIO.getComponent(), "cell 2 0,grow, wrap");
    JPanel c = new JPanel();
    c.add(ioBarChart.getComponent());
    add(c, "cell 2 0 2 1,grow");
    c.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    xyCPU = (XYTimeChartPanel) ChartBuilder.startXY().setTitle("CPU").setYAxisLabel("Percentage cpu used")
            .toChart();
    xyMemory = (XYTimeChartPanel) ChartBuilder.startXY().setTitle("Memory").setYAxisLabel("MBytes free")
            .toChart();
    xyIORx = (XYTimeChartPanel) ChartBuilder.startXY().setTitle("Network IO").setYAxisLabel("KBytes/sec")
            .toChart();
    xyIOTx = (XYTimeChartPanel) ChartBuilder.startXY().setTitle("Network IO").setYAxisLabel("KBytes/sec")
            .toChart();

    // add(xyCPU.getComponent(), "cell 0 1,grow");
    JPanel d = new JPanel();
    d.add(xyCPU.getComponent());
    add(d, "cell 0 1,grow");
    d.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    // add(xyMemory.getComponent(), "cell 1 1,grow");
    JPanel e = new JPanel();
    e.add(xyMemory.getComponent());
    add(e, "cell 1 1,grow");
    e.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    JPanel f = new JPanel();
    f.add(xyIORx.getComponent());
    add(f, "cell 2 1,grow");
    f.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    JPanel g = new JPanel();
    g.add(xyIOTx.getComponent());
    add(g, "cell 3 1,grow");
    g.setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));

    timer = TimerUtils.every("MachineTelemetryPanel-Updater", 500, TimeUnit.MILLISECONDS, new Runnable() {
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateInternal2();
                }
            });

        }
    });
}