Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

In this page you can find the example usage for javax.swing SwingWorker execute.

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:screenieup.MixtapeUpload.java

private void startUpload(byte[] b) {
    SwingWorker uploader;
    uploader = new SwingWorker<Void, Integer>() {
        @Override//from w w  w. j av  a2s  .  com
        protected Void doInBackground() throws IOException { // not handled anywhere, do fix
            publish(0);
            publish(2);
            HttpURLConnection connection = connect();
            publish(3);
            try {
                send(b, connection);
            } catch (SSLHandshakeException ex) {
                JOptionPane.showMessageDialog(null,
                        "You need to add Let's Encrypt's certificates to your Java CA Certificate store.");
                return null;
            }
            publish(4);
            String response = getResponse(connection);
            System.out.println("response received: " + response);
            parseResponse(response);
            return null;
        }

        @Override
        protected void done() {
            publish(6);
            copyToClipBoard(mixtapeurl);
            publish(7);
            urlarea.setText(mixtapeurl);
            urlarea.setEnabled(true);
            browserBtn.setEnabled(true);
            new ListWriter("mixtape_links.txt").writeList("Image link: " + mixtapeurl, true); // true = append to file, false = overwrite
            JOptionPane.showMessageDialog(null, "Uploaded!\n"
                    + "The image link has been copied to your clipboard!\nImage link has been logged to file.");
            progressDialog.dispose();
        }

        @Override
        protected void process(List<Integer> chunks) {
            progressLabel.setText(progressText[chunks.get(chunks.size() - 1)]); // The last value in this array is all we care about.
            progressBar.setValue(chunks.get(chunks.size() - 1) + 1);
        }
    };
    uploader.execute();
}

From source file:screenieup.PomfUpload.java

private void startUpload(byte[] b) {
    SwingWorker uploader;
    uploader = new SwingWorker<Void, Integer>() {
        @Override//from w  w w  . j ava 2s. co m
        protected Void doInBackground() throws IOException { // not handled anywhere, do fix
            publish(0);
            publish(2);
            HttpURLConnection connection = connect();
            publish(3);
            try {
                send(b, connection);
            } catch (SSLHandshakeException ex) {
                JOptionPane.showMessageDialog(null,
                        "You need to add Let's Encrypt's certificates to your Java CA Certificate store.");
                return null;
            }
            publish(4);
            String response = getResponse(connection);
            System.out.println("response received: " + response);
            parseResponse(response);
            return null;
        }

        @Override
        protected void done() {
            publish(6);
            copyToClipBoard(pomfurl);
            publish(7);
            urlarea.setText(pomfurl);
            urlarea.setEnabled(true);
            browserBtn.setEnabled(true);
            new ListWriter("pomf_links.txt").writeList("Image link: " + pomfurl, true); // true = append to file, false = overwrite
            JOptionPane.showMessageDialog(null, "Uploaded!\n"
                    + "The image link has been copied to your clipboard!\nImage link has been logged to file.");
            progressDialog.dispose();
        }

        @Override
        protected void process(List<Integer> chunks) {
            progressLabel.setText(progressText[chunks.get(chunks.size() - 1)]); // The last value in this array is all we care about.
            progressBar.setValue(chunks.get(chunks.size() - 1) + 1);
        }
    };
    uploader.execute();
}

From source file:screenieup.UguuUpload.java

private void startUpload(byte[] b) {
    SwingWorker uploader;
    uploader = new SwingWorker<Void, Integer>() {
        @Override//from   w ww  .  j a v  a  2  s  .c  om
        protected Void doInBackground() throws IOException { // not handled anywhere, do fix
            publish(0);
            publish(2);
            HttpURLConnection connection = connect();
            publish(3);
            send(b, connection);
            publish(4);
            uguurl = getResponse(connection);
            System.out.println("response received: " + uguurl);
            return null;
        }

        @Override
        protected void done() {
            publish(6);
            copyToClipBoard(uguurl);
            publish(7);
            urlarea.setText(uguurl);
            urlarea.setEnabled(true);
            browserBtn.setEnabled(true);
            new ListWriter("uguu_links.txt").writeList("Image link: " + uguurl, true); // true = append to file, false = overwrite
            JOptionPane.showMessageDialog(null, "Uploaded!\n"
                    + "The image link has been copied to your clipboard!\nImage link has been logged to file.");
            progressDialog.dispose();
        }

        @Override
        protected void process(List<Integer> chunks) {
            progressLabel.setText(progressText[chunks.get(chunks.size() - 1)]); // The last value in this array is all we care about.
            progressBar.setValue(chunks.get(chunks.size() - 1) + 1);
        }
    };
    uploader.execute();
}

From source file:tauargus.gui.PanelTable.java

private void buttonSuppressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSuppressActionPerformed
    JFrame parentFrame = getParentFrame();
    SuppressionMethod Soort = SuppressionMethod.GHMITER;
    if (radioButtonHyperCube.isSelected())
        Soort = SuppressionMethod.GHMITER;
    if (radioButtonModular.isSelected())
        Soort = SuppressionMethod.HITAS;
    if (radioButtonOptimal.isSelected())
        Soort = SuppressionMethod.OPTIMAL;
    if (radioButtonMarginal.isSelected())
        Soort = SuppressionMethod.MARGINAL;
    if (radioButtonNetwork.isSelected())
        Soort = SuppressionMethod.NETWORK;
    if (radioButtonUwe.isSelected())
        Soort = SuppressionMethod.UWE;//from   w w  w . j ava  2s  . co  m
    if (radioButtonCta.isSelected())
        Soort = SuppressionMethod.CTA;
    if (radioButtonRounding.isSelected())
        Soort = SuppressionMethod.ROUNDING;

    if (Soort.isAdditivityDesirable() && !tableSet.isAdditive) {
        if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this,
                "Table is not additive. Optimisation routines might be tricky\nDo you want to proceed?",
                "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) {
            return;
        }
    }

    if (Soort.isUsingSuppliedCostFunction()) {
        if (tableSet.costFunc == TableSet.COST_DIST && !Soort.canUseDistanceFunction()) {
            JOptionPane.showMessageDialog(null, "Distance function is not available for this solution");
            return;
        }
    }

    CellStatusStatistics statistics = tableSet.getCellStatusStatistics();
    if (statistics == null) {
        return; // TODO Show message
    }
    int totalUnsafeCells = statistics.totalPrimaryUnsafe();

    if (!Soort.isCosmetic()) {
        if (totalUnsafeCells == 0) {
            JOptionPane.showMessageDialog(this, "No unsafe cells found\nNo protection required");
            return;
        }
    }

    if (Soort == SuppressionMethod.OPTIMAL && totalUnsafeCells > 50) {
        if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this,
                "This tabel contains " + totalUnsafeCells
                        + " unsafe cells\nthis might take a long time; do you want to proceed?",
                "Question", JOptionPane.YES_NO_OPTION)) {
            return;
        }
    }

    if (Soort.isMinMaxTableValueNeeded()) {
        if (!VraagMinTabVal(Soort, tableSet)) {
            return;
        }
    }

    switch (Soort) {
    case ROUNDING:
        if (Application.solverSelected == Application.SOLVER_CPLEX) {
            JOptionPane.showMessageDialog(null,
                    "Whether controlled rounding can be used when Cplex is selected as solver, depends on your specific license",
                    "", JOptionPane.ERROR_MESSAGE);
        }
        //else
        DialogRoundingParameters paramsR = new DialogRoundingParameters(parentFrame, true);
        if (paramsR.showDialog(tableSet) == DialogRoundingParameters.APPROVE_OPTION) {
            final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>(
                    ProgressSwingWorker.ROUNDER, "Rounding") {
                @Override
                protected Integer doInBackground() throws ArgusException, Exception {
                    super.doInBackground();
                    OptiSuppress.runRounder(tableSet, getPropertyChangeListener());
                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    try {
                        get();
                        JOptionPane.showMessageDialog(null,
                                "The table has been rounded\n" + "Number of steps: " + tableSet.roundMaxStep
                                        + "\n" + "Max step: "
                                        + StrUtils.formatDouble(tableSet.roundMaxJump,
                                                tableSet.respVar.nDecimals)
                                        + "\n" + "Processing time: "
                                        + StrUtils.timeToString(tableSet.processingTime));
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (InterruptedException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                    }
                }
            };

            worker.execute();
            /*                try{
            OptiSuppress.runRounder(tableSet);
            JOptionPane.showMessageDialog(null, "The table has been rounded\n" +
                        "Number of steps: " + tableSet.roundMaxStep+"\n"+
                        "Max step: " + 
                        StrUtils.formatDouble(tableSet.roundMaxJump, tableSet.respVar.nDecimals)  +"\n"+
                        "Processing time: " + StrUtils.timeToString(tableSet.processingTime));
            ((AbstractTableModel)table.getModel()).fireTableDataChanged();
            adjustColumnWidths();
            updateSuppressButtons();
                            }
            // Anco 1.6                
            //                catch (ArgusException | IOException ex) {
                            catch (ArgusException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());}
                            catch (IOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
                            }*/
        }
        break;
    case CTA: //do CTA
        final int i = JOptionPane.showConfirmDialog(parentFrame, "Do you prefer to use the expert version?",
                "Select CTA version", JOptionPane.YES_NO_CANCEL_OPTION);
        if ((i == JOptionPane.YES_OPTION) || (i == JOptionPane.NO_OPTION)) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        OptiSuppress.RunCTA(tableSet, (i == JOptionPane.YES_OPTION));
                        JOptionPane.showMessageDialog(null,
                                "The CTA procedure has been completed\n" + tableSet.nSecond
                                        + " cells have been modified\n"
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (ArgusException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    } catch (FileNotFoundException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            }.start();
        }
        break;
    case UWE:
        DialogModularParameters uweParams = new DialogModularParameters(parentFrame, tableSet, false, true);
        if (uweParams.showDialog() == DialogModularParameters.APPROVE_OPTION) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        OptiSuppress.runUWE(tableSet);
                        JOptionPane.showMessageDialog(null,
                                "The UWE procedure has finished the protection\n" + tableSet.nSecond
                                        + " cells have been suppressed\n"
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (ArgusException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            }.start();
        }
        break;
    case GHMITER:
        DialogHypercubeParameters paramsG = new DialogHypercubeParameters(parentFrame, true);
        if (paramsG.showDialog(tableSet) == DialogHypercubeParameters.APPROVE_OPTION) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        GHMiter.RunGHMiter(tableSet);
                        JOptionPane.showMessageDialog(null,
                                "The Hypercube has finished the protection\n" + tableSet.nSecond
                                        + " cells have been suppressed\n" + tableSet.ghMiterMessage
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        //                              tableSet.suppressed = TableSet.SUP_GHMITER;
                        if (argus.utils.TauArgusUtils.ExistFile(Application.getTempFile("frozen.txt"))) {
                            DialogInfo Info = new DialogInfo(getParentFrame(), true);
                            Info.addLabel("Overview of the frozen cells");
                            try {
                                Info.addTextFile(Application.getTempFile("frozen.txt"));
                            } catch (ArgusException ex1) {
                            }
                            ;
                            Info.setVisible(true);
                        }
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (ArgusException ex) {

                        JOptionPane.showMessageDialog(null, ex.getMessage());
                        if (GHMiter.ShowProto002) {
                            DialogInfo Info = new DialogInfo(getParentFrame(), true);
                            Info.addLabel("Overview of the file PROTO002");
                            Info.setSize(1000, 500);
                            Info.setLocationRelativeTo(null);
                            try {
                                Info.addTextFile(Application.getTempFile("PROTO002"));
                            } catch (ArgusException ex1) {
                            }
                            ;
                            Info.setVisible(true);
                        }
                    }
                }
            }.start();
        }
        // run hypercube method
        break;
    /*            case HITAS:
    DialogModularParameters params = new DialogModularParameters(parentFrame, tableSet, false, true);
    params.showDialog();
    try {
        boolean oke = OptiSuppress.runModular(tableSet);
        JOptionPane.showMessageDialog(this, "Modular has finished the protection\n"
            + tableSet.nSecond + " cells have been suppressed\n"
            + StrUtils.timeToString(tableSet.processingTime) + " needed");
    } //|FileNotFoundException
    catch (ArgusException | IOException ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage());
    }
    break;
    */
    case HITAS:
        DialogModularParameters params = new DialogModularParameters(parentFrame, tableSet, false, true);
        if (params.showDialog() == DialogModularParameters.APPROVE_OPTION) {
            final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>(
                    ProgressSwingWorker.DOUBLE, "Modular approach") {
                @Override
                protected Integer doInBackground() throws ArgusException, Exception {
                    super.doInBackground();
                    OptiSuppress.runModular(tableSet, getPropertyChangeListener());
                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    try {
                        get();
                        JOptionPane.showMessageDialog(null,
                                "Modular has finished the protection\n" + tableSet.nSecond
                                        + " cells have been suppressed\n"
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        tableSet.undoAudit();
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (InterruptedException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                    }
                }
            };
            worker.execute();
        }
        break;
    case OPTIMAL:
        /*               params = new DialogModularParameters(parentFrame, tableSet, true, true);
        params.showDialog();
        try{
        OptiSuppress.runOptimal(tableSet);
        JOptionPane.showMessageDialog(null, "Optimal has finished the protection\n"
            + tableSet.nSecond + " cells have been suppressed\n"
                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
        tableSet.hasBeenAudited = false;
        } catch (ArgusException| IOException  ex)
        {JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        // run optimal
        */
        params = new DialogModularParameters(parentFrame, tableSet, true, true);
        if (params.showDialog() == DialogModularParameters.APPROVE_OPTION) {
            final SwingWorker<Void, Void> worker = new ProgressSwingWorker<Void, Void>(
                    ProgressSwingWorker.VALUES, "Optimal approach") {

                // called in a separate thread...
                @Override
                protected Void doInBackground() throws ArgusException, Exception {
                    super.doInBackground();
                    OptiSuppress.runOptimal(tableSet, getPropertyChangeListener(),
                            checkBoxInverseWeight.isSelected(), false, 1);
                    return null;
                }

                // called on the GUI thread
                @Override
                protected void done() {
                    super.done();
                    try {
                        get();
                        JOptionPane.showMessageDialog(null,
                                "Optimal has finished the protection\n" + tableSet.nSecond
                                        + " cells have been suppressed\n"
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        tableSet.undoAudit();
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (InterruptedException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                    }
                }
            };
            worker.execute();
        }
        break;
    case NETWORK:
        try {
            OptiSuppress.TestNetwork(tableSet);
        } catch (ArgusException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            break;
        }
        DialogNetwork paramsN = new DialogNetwork(parentFrame, true, tableSet);
        if (paramsN.showDialog() == DialogRoundingParameters.APPROVE_OPTION) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        OptiSuppress.RunNetwork(tableSet);
                        JOptionPane.showMessageDialog(null,
                                "The network has finished the protection\n" + tableSet.nSecond
                                        + " cells have been suppressed\n"
                                        + StrUtils.timeToString(tableSet.processingTime) + " needed");
                        ((AbstractTableModel) table.getModel()).fireTableDataChanged();
                        adjustColumnWidths();
                        updateSuppressButtons();
                    } catch (ArgusException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            }.start();
        }
        break;
    case MARGINAL: {
        JOptionPane.showMessageDialog(null, "The marginal method still has to be implemented");
    }
    }
    //updateSuppressButtons(); // Needs to be at each try{} of "done"because it will not wait for finishing of ProcessSwingWorker
    //        Suppress(tableIndex, false, Soort);
    tableSet.undoAudit();

    // TODO Optimalisation: Only do this if a suppression method has run
    //((AbstractTableModel)table.getModel()).fireTableDataChanged();
    //adjustColumnWidths();
}

From source file:tauargus.model.batch.java

/**
 * Read the <SUPPRESS> command in a batch file with all its parameters 
 * and calls the required suppression method
 * @throws ArgusException /*from w  ww. j a  v a 2s  .  c om*/
 */
static void suppressBatch() throws ArgusException {
    String SuppressType, token;
    int i;
    boolean linked;
    String[] tail = new String[1];
    String hs;
    final TableSet tableset;

    SuppressType = tokenizer.nextField("(").toUpperCase();
    tail[0] = tokenizer.getLine();
    tokenizer.clearLine();
    token = nextToken(tail);
    int n = Integer.parseInt(token);
    if (n < 0 || n > TableService.numberOfTables()) {
        throw new ArgusException("Wrong table number in Suppression");
    }
    linked = (n == 0);
    if (linked) {
        if (!SuppressType.equals("GH") && !SuppressType.equals("MOD")) {
            throw new ArgusException("Linked tables is only possible for Modular or Hypercube");
        }
        for (i = 0; i < TableService.numberOfTables(); i++) {
            TableService.undoSuppress(i);
        }
        tableset = tauargus.service.TableService.getTable(0);
    } else {
        tableset = tauargus.service.TableService.getTable(n - 1);
        TableService.undoSuppress(n - 1);
    }

    switch (SuppressType) {
    case "GH": {//TabNo, A priori Bounds Percentage, ModelSize, ApplySingleton) 
        token = nextChar(tail);
        if (token.equals(",")) {
            token = nextToken(tail);
            tableset.ghMiterAprioryPercentage = Integer.parseInt(token);
            token = nextChar(tail);
        }
        if (token.equals(",")) {
            token = nextToken(tail);
            tableset.ghMiterSize = Integer.parseInt(token);
            token = nextChar(tail);
        }
        if (token.equals(",")) {
            token = nextToken(tail);
            tableset.ghMiterApplySingleton = token.equals("1");
            token = nextChar(tail);
        }
        if (linked) {
            LinkedTables.buildCoverTable();
            LinkedTables.runLinkedGHMiter();
            hs = "";
            TableSet ts;
            for (i = 0; i < TableService.numberOfTables(); i++) {
                ts = tauargus.service.TableService.getTable(i);
                hs = hs + ts.CountSecondaries() + " cells have been suppressed in table " + (i + 1) + "\n";
            }
            hs = hs.substring(0, hs.length() - 1);
        } else {
            GHMiter.RunGHMiter(tableset);
            hs = tableset.CountSecondaries() + " cells have been suppressed";
        }
        reportProgress("The hypercube procedure has been applied\n" + hs);
        break;
    }
    case "MOD": {//TabNo, MaxTimePerSubtable
        token = nextChar(tail);
        if (token.equals(",")) {
            token = nextToken(tail);
            tableset.maxHitasTime = Integer.parseInt(token);
            Application.generalMaxHitasTime = tableset.maxHitasTime;
            // The generalMAxHitasTime is used in the runModular procedure.
            token = nextChar(tail);
        }
        i = 0;
        while (token.equals(",") && (i < 3)) {
            i++;
            token = nextToken(tail);
            switch (i) {
            case 1:
                tableset.singletonSingletonCheck = token.equals("1");
                break;
            case 2:
                tableset.singletonMultipleCheck = token.equals("1");
                break;
            case 3:
                tableset.minFreqCheck = token.equals("1");
                break;
            }
            token = nextChar(tail);

        }
        if (linked) {
            LinkedTables.buildCoverTable();
            LinkedTables.runLinkedModular(null);
        } else { // single table
            if (token.equals(",")) { //MSC specified
                token = nextToken(tail);
                tableset.maxScaleCost = StrUtils.toDouble(token);
                if (tableset.maxScaleCost <= 0) {
                    throw new ArgusException("Illegal Max Scaling Cost: " + token);
                }
            }

            try { // Make sure that PropertyChanges are not processed in batch-mode by overriding propertyChange to do nothing
                if (Application.batchType() == Application.BATCH_COMMANDLINE) {
                    OptiSuppress.runModular(tableset, new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                        }
                    });
                    reportProgressInfo("The modular procedure has been applied\n" + tableset.CountSecondaries()
                            + " cells have been suppressed");
                } else {
                    final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>(
                            ProgressSwingWorker.DOUBLE, "Modular approach") {
                        @Override
                        protected Integer doInBackground() throws ArgusException, Exception {
                            super.doInBackground();
                            OptiSuppress.runModular(tableset, getPropertyChangeListener());
                            reportProgressInfo("The modular procedure has been applied\n"
                                    + tableset.CountSecondaries() + " cells have been suppressed");
                            return null;
                        }

                        @Override
                        protected void done() {
                            super.done();
                            try {
                                get();
                                tableset.undoAudit();
                                // Wat doet dit? Hoeft niet. Alleen voor GUI                            
                                //                            ((AbstractTableModel)table.getModel()).fireTableDataChanged();
                            } catch (InterruptedException ex) {
                                logger.log(Level.SEVERE, null, ex);
                            } catch (ExecutionException ex) {
                                JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                            }
                        }
                    };
                    worker.execute();
                    while (!worker.isDone()) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            } catch (IOException ex) {
                throw new ArgusException("Modular failed\n" + ex.getMessage());
            }
        }

        break;
    }
    case "OPT": {//TabNo, MaxComputingTime
        if (n == 0) {
            throw new ArgusException("Linked tables is not possible for Optimal");
        }
        token = nextChar(tail);
        if (token.equals(",")) {
            token = nextToken(tail);
            tableset.maxHitasTime = Integer.parseInt(token);
            token = nextChar(tail);
        }

        if (Application.batchType() == Application.BATCH_COMMANDLINE) {
            try {
                OptiSuppress.runOptimal(tableset, new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                    }
                }, false, false, 1);
            } catch (IOException ex) {
            }
        } else { // From menu with swingworker
            final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>(
                    ProgressSwingWorker.DOUBLE, "Modular approach") {
                @Override
                protected Integer doInBackground() throws ArgusException, Exception {
                    super.doInBackground();
                    try {
                        OptiSuppress.runOptimal(tableset, new PropertyChangeListener() {
                            @Override
                            public void propertyChange(PropertyChangeEvent evt) {
                            }
                        }, false, false, 1);
                    } catch (IOException ex) {
                    }
                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    try {
                        get();
                    } catch (InterruptedException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                    }
                }
            };
            worker.execute();
            while (!worker.isDone()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }
        }

        //TODO
        reportProgressInfo("The optimal procedure has been applied\n" + tableset.CountSecondaries()
                + " cells have been suppressed");

        break;
    }
    case "RND": {//TabNo, RoundingBase, Steps, Time, Partitions, StopRule
                 // OK after Roundbase: Default Step = 0 (no step), time = 10, Nopartitions part = 0, stoprule = 2(optimal)
        if (n == 0) {
            throw new ArgusException("Linked tables is not possible for Rounding");
        }
        if (Application.solverSelected == Application.SOLVER_CPLEX)
        //{throw new ArgusException("Controlled rounding cannot be used when Cplex is selected as solver");}
        {
            reportProgressInfo(
                    "Whether controlled rounding can be used when Cplex is selected as solver, depends on your specific license.\n Incorrect license may cause errors.");
        }
        token = nextChar(tail);
        if (!token.equals(",")) {
            throw new ArgusException("a komma(,) expected");
        }
        token = nextToken(tail);
        tableset.roundBase = Integer.parseInt(token);
        long mrb = TableSet.computeMinRoundBase(tableset);
        if (tableset.roundBase < mrb) {
            throw new ArgusException(
                    "The rounding base is too small\n" + "A minimum of " + mrb + " is required");
        }
        //set the defaults
        tableset.roundMaxStep = 0;
        tableset.roundMaxTime = 10;
        tableset.roundPartitions = 0;
        tableset.roundStoppingRule = 2;
        token = nextChar(tail);

        if (token.equals(",")) { //steps
            token = nextToken(tail);
            tableset.roundMaxStep = StrUtils.toInteger(token);
            token = nextChar(tail);
        } else {
            if (!token.equals(")"))
                throw new ArgusException("a komma(,) or \")\" expected");
        }

        if (token.equals(",")) { //max time
            token = nextToken(tail);
            tableset.roundMaxTime = Integer.parseInt(token);
            if (tableset.roundMaxTime <= 0) {
                throw new ArgusException("Illegal value for max time: " + tableset.roundMaxTime);
            }
            token = nextChar(tail);
        } else {
            if (!token.equals(")"))
                throw new ArgusException("a komma(,) or \")\" expected");
        }

        if (token.equals(",")) { //partitions
            token = nextToken(tail);
            tableset.roundPartitions = Integer.parseInt(token);
            if (tableset.roundPartitions < 0 || tableset.roundPartitions > 1) {
                throw new ArgusException("Illegal value for partitions: " + tableset.roundPartitions);
            }
            token = nextChar(tail);
        } else {
            if (!token.equals(")"))
                throw new ArgusException("a komma(,) or \")\" expected");
        }

        if (token.equals(",")) { //Stop rule
            token = nextToken(tail);
            tableset.roundStoppingRule = Integer.parseInt(token);
            if (tableset.roundStoppingRule <= 0 || tableset.roundStoppingRule > 2) {
                throw new ArgusException("Illegal value for max time: " + tableset.roundStoppingRule);
            }
            token = nextChar(tail);
        } else {
            if (!token.equals(")"))
                throw new ArgusException("a komma(,) or \")\" expected");
        }

        if (token.equals(",")) { //Unit cost function
            token = nextToken(tail);
            if (token.equals("1")) {
                tableset.roundUnitCost = true;
            } else if (token.equals("0")) {
                tableset.roundUnitCost = false;
            } else {
                throw new ArgusException("Illegal value UnitCost parameter: only 0 or 1 allowed");
            }
            token = nextChar(tail);
        } else {
            if (!token.equals(")"))
                throw new ArgusException("a komma(,) or \")\" expected");
        }

        // all parameters have been handeled. Run the rounder.
        if (Application.batchType() == Application.BATCH_COMMANDLINE) {
            try {
                OptiSuppress.runRounder(tableset, new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                    }
                });
            } catch (IOException ex) {
                throw new ArgusException(ex.getMessage());
            }
        } else //batch run from menu
        {
            final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>(
                    ProgressSwingWorker.ROUNDER, "Rounding") {
                @Override
                protected Integer doInBackground() throws ArgusException, Exception {
                    super.doInBackground();
                    try {
                        OptiSuppress.runRounder(tableset, new PropertyChangeListener() {
                            @Override
                            public void propertyChange(PropertyChangeEvent evt) {
                            }
                        });
                    } catch (IOException ex) {
                    }
                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    try {
                        get();
                    } catch (InterruptedException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        JOptionPane.showMessageDialog(null, ex.getCause().getMessage());
                    }
                }
            };
            worker.execute();
            while (!worker.isDone()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }
        }
        reportProgressInfo("The table has been rounded\n" + "Number of steps: " + tableset.roundMaxStep + "\n"
                + "Max step: " + StrUtils.formatDouble(tableset.roundMaxJump, tableset.respVar.nDecimals));
        break;
    }
    case "CTA": {
        try {
            OptiSuppress.RunCTA(tableset, false);
            reportProgress("CTA run completed");
        } catch (IOException ex) {
            throw new ArgusException(ex.getMessage());
        }
        break;
    }
    case "NET": {
        OptiSuppress.TestNetwork(tableset);

        OptiSuppress.RunNetwork(tableset);

        break;
    }
    default:
        throw new ArgusException("Unknown suppression method (" + SuppressType + ") found");
    }

}

From source file:ui.frame.UILogin.java

public UILogin() {
    super("Login");

    Label l = new Label();

    setLayout(new BorderLayout());
    this.setPreferredSize(new Dimension(400, 300));

    Panel p = new Panel();

    loginPanel = p.createPanel(Layouts.grid, 4, 2);
    loginPanel.setBorder(new EmptyBorder(25, 25, 0, 25));
    lblUser = l.createLabel("Username:");
    lblPassword = l.createLabel("Password:");
    lblURL = l.createLabel("Server URL");
    lblBucket = l.createLabel("Bucket");

    tfURL = new JTextField();
    tfURL.setText("kaiup.kaisquare.com");
    tfBucket = new JTextField();
    PromptSupport.setPrompt("BucketName", tfBucket);
    tfUser = new JTextField();
    PromptSupport.setPrompt("Username", tfUser);
    pfPassword = new JPasswordField();
    PromptSupport.setPrompt("Password", pfPassword);

    buttonPanel = p.createPanel(Layouts.flow);
    buttonPanel.setBorder(new EmptyBorder(0, 0, 25, 0));
    Button b = new Button();
    JButton btnLogin = b.createButton("Login");
    JButton btnExit = b.createButton("Exit");
    btnLogin.setPreferredSize(new Dimension(150, 50));
    btnExit.setPreferredSize(new Dimension(150, 50));
    Component[] arrayBtn = { btnExit, btnLogin };
    p.addComponentsToPanel(buttonPanel, arrayBtn);

    Component[] arrayComponents = { lblURL, tfURL, lblBucket, tfBucket, lblUser, tfUser, lblPassword,
            pfPassword };/*from w  w w.j a v  a  2  s .  c o  m*/
    p.addComponentsToPanel(loginPanel, arrayComponents);
    add(loginPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);
    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    setVisible(true);
    btnLogin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    if (tfUser.getText().equals("") || String.valueOf(pfPassword.getPassword()).equals("")
                            || tfBucket.getText().equals("")) {
                        JOptionPane.showMessageDialog(Data.mainFrame, "Please fill up all the fields", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        String username = tfUser.getText();
                        String password = String.valueOf(pfPassword.getPassword());
                        Data.URL = Data.protocol + tfURL.getText();
                        Data.targetURL = Data.protocol + tfURL.getText() + "/api/" + tfBucket.getText() + "/";

                        String response = api.loginBucket(Data.targetURL, username, password);

                        try {

                            if (DesktopAppMain.checkResult(response)) {
                                JSONObject responseJSON = new JSONObject(response);
                                Data.sessionKey = responseJSON.get("session-key").toString();
                                response = api.getUserFeatures(Data.targetURL, Data.sessionKey);
                                if (checkFeatures(response)) {
                                    Data.mainFrame = new KAIQRFrame();
                                    Data.mainFrame.uiInventorySelect = new UIInventorySelect();
                                    Data.mainFrame.addPanel(Data.mainFrame.uiInventorySelect, "inventory");
                                    Data.mainFrame.showPanel("inventory");
                                    Data.mainFrame.pack();
                                    setVisible(false);
                                    Data.mainFrame.setVisible(true);

                                } else {
                                    JOptionPane.showMessageDialog(Data.loginFrame,
                                            "User does not have necessary features", "Error",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                            } else {
                                JOptionPane.showMessageDialog(Data.loginFrame, "Wrong username/password",
                                        "Error", JOptionPane.ERROR_MESSAGE);
                            }

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

                    return null;
                }
            };

            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Login", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });

            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Logging in .........."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });

    btnExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }

    });

}

From source file:ui.panel.UIAccessKeySelect.java

public void runaccessKeySelect() {
    getAccessKeyData();//  w  w w .jav a 2 s . co  m
    Panel p = new Panel();
    Button b = new Button();
    Label l = new Label();

    setLayout(new BorderLayout());

    JPanel pnlInstruction = p.createPanel(Layouts.flow);
    JLabel lblInstruction = l.createLabel("Access Keys");
    pnlInstruction.setBackground(CustomColor.LightBlue.returnColor());
    lblInstruction.setForeground(Color.white);
    lblInstruction.setFont(new Font("San Serif", Font.PLAIN, 18));
    pnlInstruction.add(lblInstruction);

    JPanel pnlBucketList = p.createPanel(Layouts.border);

    listBucket.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollBucket = new JScrollPane(listBucket);
    Component[] BucketListComponents = { scrollBucket };
    pnlBucketList.add(scrollBucket, BorderLayout.CENTER);

    JPanel pnlButtons = p.createPanel(Layouts.flow);

    JButton btnBack = b.createButton("Back");
    JButton btnSelectElements = b.createButton("Next");
    JButton btnAdd = b.createButton("Generate Access Key");
    JButton btnRefresh = b.createButton("Refresh");

    pnlButtons.add(btnBack);
    pnlButtons.add(btnAdd);
    pnlButtons.add(btnRefresh);
    pnlButtons.add(btnSelectElements);

    add(pnlInstruction, BorderLayout.NORTH);
    add(pnlBucketList, BorderLayout.CENTER);
    add(pnlButtons, BorderLayout.SOUTH);

    btnBack.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.showPanel("license");
        }
    });

    btnRefresh.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getAccessKeyData();
        }
    });
    btnAdd.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.uiGenerateKey = new UIGenerateKey();
            Data.mainFrame.addPanel(Data.mainFrame.uiGenerateKey, "generateKey");
            Data.mainFrame.pack();
            Data.mainFrame.showPanel("generateKey");
        }
    });

    btnSelectElements.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    int selected = listBucket.getSelectedRow();

                    if (selected != -1) {
                        Data.accessKey = (String) listBucket.getModel().getValueAt(selected, 0);
                        Data.mainFrame.qrGenerator = new JavaQR();
                        Data.mainFrame.pack();
                        Data.mainFrame.addPanel(Data.mainFrame.qrGenerator, "generateQR");
                        Data.mainFrame.showPanel("generateQR");
                    } else {
                        JOptionPane.showMessageDialog(Data.mainFrame, "Please Select Access Key", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }
            };

            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Loading", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });
            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Generating QR Code......."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });
}

From source file:ui.panel.UIBucketSelect.java

public void runBucketSelect() {
    Panel p = new Panel();
    Button b = new Button();
    Label l = new Label();

    setLayout(new BorderLayout());

    JPanel pnlInstruction = p.createPanel(Layouts.flow);
    JLabel lblInstruction = l.createLabel("Bucket List");
    pnlInstruction.setBackground(CustomColor.LightBlue.returnColor());
    lblInstruction.setForeground(Color.white);
    lblInstruction.setFont(new Font("San Serif", Font.PLAIN, 18));
    pnlInstruction.add(lblInstruction);//  w  w w  .  ja  v  a 2 s.co  m

    JPanel pnlBucketList = p.createPanel(Layouts.border);

    listBucket.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollBucket = new JScrollPane(listBucket);
    scrollBucket.setPreferredSize(new Dimension(300, 150));
    pnlBucketList.add(scrollBucket, BorderLayout.CENTER);

    JPanel pnlButtons = p.createPanel(Layouts.flow);
    JButton btnBack = b.createButton("Back");
    JButton btnSelectElements = b.createButton("Next");
    JButton btnRefresh = b.createButton("Refresh Bucket List");

    pnlButtons.add(btnBack);
    pnlButtons.add(btnRefresh);
    pnlButtons.add(btnSelectElements);

    add(pnlInstruction, BorderLayout.NORTH);
    add(pnlBucketList, BorderLayout.CENTER);
    add(pnlButtons, BorderLayout.SOUTH);
    setVisible(true);

    btnRefresh.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            getBucketData();
        }
    });
    btnSelectElements.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {

                    int selected = listBucket.getSelectedRow();
                    if (selected == -1) {
                        JOptionPane.showMessageDialog(Data.mainFrame, "Please Select a Bucket", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        Data.bucketID = (int) listBucket.getModel().getValueAt(selected, 0);
                        Data.mainFrame.addPanel(Data.mainFrame.uiLicenseDetail = new UILicenseDetail(),
                                "license");
                        Data.mainFrame.pack();
                        Data.mainFrame.showPanel("license");
                    }
                    return null;
                }
            };

            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Loading", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });
            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Retrieving Licenses......."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });
    btnBack.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            Data.mainFrame.showPanel("inventory");
        }
    });
}

From source file:ui.panel.UILicenseAdd.java

public JPanel createButtonPanel() {
    JPanel panel = p.createPanel(Layouts.flow);
    panel.setLayout(new FlowLayout(FlowLayout.CENTER));

    btnSubmit = b.createButton("Submit");
    btnCancel = b.createButton("Cancel");

    btnSubmit.addActionListener(new ActionListener() {

        @Override/*from  w  w  w  . j  a  v  a2 s.  c  o  m*/
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    TreePath[] path = checkTreeManager.getSelectionModel().getSelectionPaths();
                    ArrayList<String> featureL = new ArrayList<String>();
                    String[] features = new String[] {};
                    for (TreePath tp : path) {

                        if (tp.getLastPathComponent().toString().equals("Features")) {
                            Object rootNode = tree.getModel().getRoot();
                            int parentCount = tree.getModel().getChildCount(rootNode);
                            for (int i = 0; i < parentCount; i++) {
                                Object parentNode = tree.getModel().getChild(rootNode, i);
                                int childrenCount = tree.getModel().getChildCount(parentNode);

                                for (int x = 0; x < childrenCount; x++) {
                                    MyDataNode node = (MyDataNode) tree.getModel().getChild(parentNode, x);
                                    featureL.add(node.getValue());
                                }
                            }
                        } else if (tp.getPathCount() == 2) {
                            Object rootNode = tree.getModel().getRoot();
                            int parentCount = tree.getModel().getChildCount(rootNode);
                            for (int i = 0; i < parentCount; i++) {
                                Object parentNode = tree.getModel().getChild(rootNode, i);
                                if (parentNode.toString().equals(tp.getLastPathComponent().toString())) {

                                    int childrenCount = tree.getModel().getChildCount(parentNode);

                                    for (int x = 0; x < childrenCount; x++) {
                                        MyDataNode node = (MyDataNode) tree.getModel().getChild(parentNode, x);
                                        featureL.add(node.getValue());
                                    }
                                }
                            }
                        } else if (tp.getPathCount() == 3) {
                            MyDataNode node = (MyDataNode) tp.getLastPathComponent();
                            featureL.add(node.getValue());
                        }

                    }
                    features = featureL.toArray(features);
                    String duration = spnValidity.getValue().toString();
                    if (cbPerpetual.isSelected()) {
                        duration = "-1";
                    }
                    String storage = spnCloud.getValue().toString();
                    String maxVCA = spnConcurrentVCA.getValue().toString();
                    String response = apiCall.addNodeLicense(Data.targetURL, Data.sessionKey, Data.bucketID,
                            features, duration, storage, maxVCA);

                    try {
                        JSONObject responseObject = new JSONObject(response);
                        if (responseObject.get("result").equals("ok")) {
                            Data.mainFrame.uiLicenseDetail.getLicenseData();
                            Data.mainFrame.showPanel("license");
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    return null;
                }
            };
            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Loading", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });
            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Retrieving License..."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });

    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            Data.mainFrame.showPanel("license");
        }
    });

    panel.add(btnSubmit);
    panel.add(btnCancel);

    return panel;
}

From source file:ui.panel.UILicenseDetail.java

public JPanel createButtonPanel() {
    JPanel panel = p.createPanel(Layouts.flow);
    panel.setLayout(new FlowLayout(FlowLayout.CENTER));

    btnSubmit = b.createButton("Next");
    btnBack = b.createButton("Back");
    btnAdd = b.createButton("Add License");

    panel.add(btnBack);//from  w ww . j ava  2  s .  c o m
    panel.add(btnAdd);
    panel.add(btnSubmit);
    btnBack.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.showPanel("bucket");
        }
    });

    btnAdd.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.addPanel(Data.mainFrame.uiLicenseAdd = new UILicenseAdd(), "licenseAdd");
            Data.mainFrame.showPanel("licenseAdd");
        }
    });
    btnSubmit.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    int row = tblInfo.getSelectedRow();
                    if (row == -1) {
                        JOptionPane.showMessageDialog(Data.mainFrame, "Please Select a License", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        Data.licenseNumber = (String) tblInfo.getModel().getValueAt(row, 0);
                        Data.mainFrame.uiAccessKeySelect = new UIAccessKeySelect();
                        Data.mainFrame.addPanel(Data.mainFrame.uiAccessKeySelect, "access");
                        Data.mainFrame.showPanel("access");
                    }

                    return null;
                }
            };

            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Loading", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });
            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Retrieving Access Keys"), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);

        }

    });

    btnBack.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            Data.mainFrame.showPanel("bucket");
        }
    });

    btnAdd.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            Data.mainFrame.addPanel(Data.mainFrame.uiLicenseAdd = new UILicenseAdd(), "licenseAdd");
            Data.mainFrame.pack();
            Data.mainFrame.showPanel("licenseAdd");
        }
    });

    return panel;
}