Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

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

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:gui_pack.MainGui.java

private void runTestsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runTestsButtonActionPerformed
    int rangeMin, rangeMax, spacing;
    int passing = 0;

    {//  Beginning of input validation
        String errorTitle, errorMessage;

        //make sure at least one sort algorithm is selected
        if (!(insertionCheckBox.isSelected() || mergeCheckBox.isSelected() || quickCheckBox.isSelected()
                || selectionCheckBox.isSelected())) {
            errorTitle = "Selection Error";
            errorMessage = "At least one sort algorithm (Insertion Sort, "
                    + "Merge Sort, Quick Sort, or Selection Sort) must be selected.";
            JOptionPane.showMessageDialog(null, errorMessage, errorTitle, JOptionPane.WARNING_MESSAGE);
            return;
        }/*from  w w w .  j a  v  a2 s .  co m*/

        //make sure at least one order is selected
        if (!(ascendingCheckBox.isSelected() || descendingCheckBox.isSelected()
                || randomCheckBox.isSelected())) {
            errorTitle = "Selection Error";
            errorMessage = "At least one order (Ascending Order, Descending Order, or Random Order) "
                    + "must be selected.";
            JOptionPane.showMessageDialog(null, errorMessage, errorTitle, JOptionPane.WARNING_MESSAGE);
            return;
        }

        //make sure all the proper fields contain data
        try {
            rangeMin = Integer.parseInt(rangeMinField.getText());
            rangeMax = Integer.parseInt(rangeMaxField.getText());
            spacing = Integer.parseInt(spacingField.getText());
            //for the multithreaded version of this program "iterations" cannot be a variable
            //this was left in to catch if the iteration field is left blank or has no value
            if (iterationField.isEnabled()) {
                Integer.parseInt(iterationField.getText());
            }
        } catch (NumberFormatException arbitraryName) {
            errorTitle = "Input Error";
            if (iterationField.isEnabled()) {
                errorMessage = "The size, intervals, and iterations fields must contain "
                        + "integer values and only integer values.";
            } else {
                errorMessage = "The size and intervals fields must contain "
                        + "integer values and only integer values.";
            }
            JOptionPane.showMessageDialog(null, errorMessage, errorTitle, JOptionPane.WARNING_MESSAGE);
            return;
        }

        //make sure field data is appropriate
        if (rangeMin > rangeMax) {
            errorTitle = "Range Error";
            errorMessage = "Minimum Size must be less than or equal to Maximum Size.";
            JOptionPane.showMessageDialog(null, errorMessage, errorTitle, JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (spacing < 1 || rangeMin < 1 || rangeMax < 1
                || (iterationField.isEnabled() && Integer.parseInt(iterationField.getText()) < 1)) {
            errorTitle = "Value Error";
            if (iterationField.isEnabled()) {
                errorMessage = "Intervals, sizes, and iterations must be in the positive domain. "
                        + "Spacing, Range(min), Range(max), and Iterations must be greater than or"
                        + " equal to one.";
            } else {
                errorMessage = "Intervals and sizes must be in the positive domain. "
                        + "Spacing, Range(min) and Range(max) be greater than or" + " equal to one.";
            }
            JOptionPane.showMessageDialog(null, errorMessage, errorTitle, JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (!iterationField.isEnabled()) {
            passing = 0;
        }

    } // End of input validation

    //here's where we set up a loading bar in case the tests take a while
    JProgressBar loadBar = new JProgressBar();
    JFrame loadFrame = new JFrame();
    JLabel displayLabel1 = new JLabel();
    loadBar.setIndeterminate(true);
    loadBar.setVisible(true);
    displayLabel1.setText("Running large tests, or many tests, using inefficient algorithms \n"
            + "may take a while. Please be patient.");
    loadFrame.setLayout(new FlowLayout());
    loadFrame.add(loadBar);
    loadFrame.add(displayLabel1);
    loadFrame.setSize(600, 100);
    loadFrame.setTitle("Loading");
    loadFrame.setVisible(true);

    //now we will leave this open until the tests are completed
    //now we can conduct the actual tests
    SwingWorker worker = new SwingWorker<XYSeriesCollection, Void>() {
        XYSeriesCollection results = new XYSeriesCollection();

        @Override
        protected XYSeriesCollection doInBackground() {
            XYSeries insertSeries = new XYSeries("Insertion Sort");
            XYSeries mergeSeries = new XYSeries("Merge Sort");
            XYSeries quickSeries = new XYSeries("Quick Sort");
            XYSeries selectSeries = new XYSeries("Selection Sort");

            final boolean ascending = ascendingCheckBox.isSelected();
            final boolean descending = descendingCheckBox.isSelected();
            final boolean insertion = insertionCheckBox.isSelected();
            final boolean merge = mergeCheckBox.isSelected();
            final boolean quick = quickCheckBox.isSelected();
            final boolean selection = selectionCheckBox.isSelected();

            final int iterations = Integer.parseInt(iterationField.getText());

            ListGenerator generator = new ListGenerator();
            int[] list;
            for (int count = rangeMin; count <= rangeMax; count = count + spacing) {

                if (ascending) {

                    list = generator.ascending(count);
                    if (insertion) {
                        insertSeries.add(count, insertionSort.sort(list));
                    }
                    if (merge) {
                        mergeSeries.add(count, mergeSort.sort(list));
                    }
                    if (quick) {
                        quickSeries.add(count, quickSort.sort(list));
                    }
                    if (selection) {
                        selectSeries.add(count, selectionSort.sort(list));
                    }
                }
                if (descending) {

                    list = generator.descending(count);
                    if (insertion) {
                        insertSeries.add(count, insertionSort.sort(list));
                    }
                    if (merge) {
                        mergeSeries.add(count, mergeSort.sort(list));
                    }
                    if (quick) {
                        quickSeries.add(count, quickSort.sort(list));
                    }
                    if (selection) {
                        selectSeries.add(count, selectionSort.sort(list));
                    }
                }

                for (int iteration = 0; iteration < iterations; iteration++) {
                    list = generator.random(count);

                    if (insertion) {
                        insertSeries.add(count, insertionSort.sort(list));
                    }
                    if (merge) {
                        mergeSeries.add(count, mergeSort.sort(list));
                    }
                    if (quick) {
                        quickSeries.add(count, quickSort.sort(list));
                    }
                    if (selection) {
                        selectSeries.add(count, selectionSort.sort(list));
                    }
                }

            }

            //now we aggregate the results
            if (insertion) {
                results.addSeries(insertSeries);
            }
            if (merge) {
                results.addSeries(mergeSeries);
            }
            if (quick) {
                results.addSeries(quickSeries);
            }
            if (selection) {
                results.addSeries(selectSeries);
            }
            return results;
        }

        @Override
        protected void done() {
            //finally, we display the results
            JFreeChart chart = ChartFactory.createScatterPlot("SortExplorer", // chart title
                    "List Size", // x axis label
                    "Number of Comparisons", // y axis label
                    results, // data  
                    PlotOrientation.VERTICAL, true, // include legend
                    true, // tooltips
                    false // urls
            );
            ChartFrame frame = new ChartFrame("First", chart);
            frame.pack();
            frame.setVisible(true);
            loadFrame.setVisible(false);
        }
    };

    //having set up the multithreading 'worker' we can finally conduct the 
    //test
    worker.execute();

}

From source file:mainGUI.TrainingJFrame.java

private void loadMNISTButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMNISTButtonActionPerformed
    mnistProgressBar.setMaximum(60000);//from   w  w w .jav a  2  s.co m

    SwingWorker<TrainingDataSet, Integer> worker = new SwingWorker<TrainingDataSet, Integer>() {
        @Override
        protected TrainingDataSet doInBackground() throws Exception {
            MNISTDatasetLoader.setOnDataitemLoadListener(new OnDataitemLoadListener() {
                @Override
                public void onDataitemLoadListener(int currentProgress) {
                    publish(currentProgress);
                }
            });
            return MNISTDatasetLoader.loadMNISTDataset("MNIST/train-images.idx3-ubyte",
                    "MNIST/train-labels.idx1-ubyte");
        }

        @Override
        protected void process(List<Integer> chunks) {
            mnistProgressBar.setValue(chunks.get(chunks.size() - 1));
            mnistProgressBar.setString(chunks.get(chunks.size() - 1) + " of 60000");
        }

        protected void done() {
            try {
                trainingDataSet = get();
                loadNetPanel.setEnabled(true);
                System.out.println("MNIST Dataset Loaded");
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                Logger.getLogger(TrainingJFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                ex.printStackTrace();
                Logger.getLogger(TrainingJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    worker.execute();
}

From source file:es.emergya.ui.gis.popups.ConsultaHistoricos.java

public synchronized void setError(final String e) {
    if (limpiarError != null && limpiarError.isAlive()) {
        limpiarError.interrupt();/*w ww  .  j a v  a2 s . c  o  m*/
    }

    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

        @Override
        protected Object doInBackground() throws Exception {
            return null;
        }

        @Override
        protected void done() {
            mensaje.setText(e);
            mensaje.repaint();
            cargando.setIcon(LogicConstants.getIcon("48x48_transparente"));
        }
    };

    sw.execute();

    limpiarError = new Thread() {

        @Override
        public void run() {
            try {
                Thread.sleep(1000 * LogicConstants.getInt("TIMEOUT_ERROR_WEBSERVICE", 15));

                SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                    @Override
                    protected Object doInBackground() throws Exception {
                        mensaje.setText("");
                        return null;
                    }
                };

                sw.execute();
            } catch (InterruptedException e) {
            }

        }
    };
    limpiarError.start();
}

From source file:es.emergya.ui.gis.CustomMapView.java

@Override
public void updateMarkers() {
    Rectangle r = getBoundingBox();
    final LatLon tl, br;
    // tomamos los pois en un area de 3 pantallas cuadradas, de manera que
    // se pueda arrastrar sin notar que no estan cargados los poi de mas
    // all, ya que solo se deberian cargar cuando deja de moverse.
    tl = getLatLon(r.x - r.width, r.y - r.height);
    br = getLatLon(r.x + 2 * r.width, r.y + 2 * r.height);

    if (mapUpdater == null || mapUpdater.isDone()) {
        mapUpdater = new SwingWorker<Object, Object>() {

            @Override/*from   w  w  w.  j a v  a  2  s. com*/
            protected Object doInBackground() throws Exception {
                try {
                    updateIncidences(tl, br);
                    updateResources(tl, br);
                } catch (Throwable t) {
                    log.error("Error al actualizar marcadores", t);
                }
                return null;
            }

            @Override
            protected void done() {
                repaint();
            }
        };

        mapUpdater.execute();

    }
}

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

private void setCorrectDocument(final MirthSyntaxTextArea textPane, final String message, String dataType) {
    // First load the plain message (without pretty printing)
    SyntaxDocument newDoc = new SyntaxDocument();
    boolean isXml = false;
    boolean isJson = false;

    if (StringUtils.isNotEmpty(message)) {
        String trimmedMessage = message.trim();
        isXml = trimmedMessage.length() > 0 && trimmedMessage.charAt(0) == '<';
        isJson = trimmedMessage.length() > 0
                && (trimmedMessage.charAt(0) == '{' || trimmedMessage.charAt(0) == '[');

        // Set token markers
        if (isXml) {
            newDoc.setTokenMarker(new XMLTokenMarker());
        } else if (isJson) {
            newDoc.setTokenMarker(new JSONTokenMarker());
        } else if (dataType != null) {
            newDoc.setTokenMarker(//from w ww  .j a v a2  s  .c  o m
                    LoadedExtensions.getInstance().getDataTypePlugins().get(dataType).getTokenMarker());
        }

        textPane.setDocument(newDoc);
        textPane.setText(message);
    } else {
        textPane.setDocument(newDoc);
        textPane.setText("");
    }

    textPane.setCaretPosition(0);

    // Pretty print (if enabled) on a separate thread since it's prone to take a while for certain DTDs
    if (formatMessageCheckBox.isSelected() && (isXml || isJson)) {
        final boolean formatXml = isXml;
        final boolean formatJson = isJson;

        final String workingId = parent.startWorking("Pretty printing...");

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            String prettifiedMessage = null;

            @Override
            public Void doInBackground() {
                if (StringUtils.isNotEmpty(message)) {
                    if (formatXml) {
                        prettifiedMessage = MirthXmlUtil.prettyPrint(message);
                    } else if (formatJson) {
                        try {
                            prettifiedMessage = MirthJsonUtil.prettyPrint(message);
                        } catch (Exception e) {
                            logger.error("Error pretty printing json.", e);
                        }
                    }
                }

                return null;
            }

            @Override
            public void done() {
                if (!isCancelled()) {
                    if (prettifiedMessage != null && StringUtils.isNotEmpty(prettifiedMessage)) {
                        textPane.setText(prettifiedMessage);
                        textPane.setCaretPosition(0);
                    }
                }

                parent.stopWorking(workingId);
            }
        };

        prettyPrintWorkers.add(worker);
        executor.submit(worker);
    }
}

From source file:com.clough.android.adbv.view.MainFrame.java

private void runQuery() {
    invalidateInputOutput();/*  w  ww  .ja v a  2  s  .  co m*/
    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            try {
                outputResult = ioManager.executeQuery(inputQuery);
                outputResultAsTextTable = "";
            } catch (IOManagerException ex) {
                showDeviceDisconnectedDialog();
            }
            inputQuery = "";
            return null;
        }

        @Override
        protected void done() {
            closeProgressDialog();
            processResult(false);
        }

    }.execute();
    showProgressDialog(true, 0, "Receiving result set");

}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

@Deprecated
public static void setupTablePopupOld() {

    JMenuItem menuItem = new JMenuItem("Start");
    menuItem.addActionListener(new ActionListener() {

        @Override/*from  w w w  .  j a  v a  2  s . co m*/
        public void actionPerformed(final ActionEvent e) {
            /*
            lockInterface();
            l.trace(e.paramString());
            int row = jTable1.rowAtPoint(new Point(Shared.guiLastTablePopupX, Shared.guiLastTablePopupY));
            String game = (String) jTable1.getModel().getValueAt(row, 0);
            l.trace("Popup action! row: " + row + " and name " + game);
            int status = GamelistStorage.getGame(game).gameStatus;
            if (status == 0) {
            File g = new File(GamelistStorage.getGame(game).gameAbsoluteFolderPath);
            File tp = new File(Utils.concatenatePaths(new String[]{Shared.workingDirectory, Shared.torrentStoreSubDirectory}));
            try {
            TOTorrent t = TrackerManager.createNewTorrent(g, tp, new ProgressListener(game));
            TrackerManager.getCore().addTorrentToTracker(t, tp.getAbsolutePath(), g.getAbsolutePath());
            } catch (Exception ex) {
            l.error("Torrent create failed: " + game, ex);
            }
            } else if (status == 1||status == 2) {
            l.error("Game torrent already created");
            } else {
            l.error("Game has been run already");
            }
            unlockInterface();
             *
             */
            SwingWorker worker = new SwingWorker<Void, Void>() {

                @Override
                public Void doInBackground() {
                    MainFrame.lockInterface();
                    l.trace(e.paramString());
                    int row = jTable1
                            .rowAtPoint(new Point(Shared.guiLastTablePopupX, Shared.guiLastTablePopupY));
                    String game = (String) jTable1.getModel().getValueAt(row, 0);
                    l.trace("Popup start action! row: " + row + " and name " + game);
                    int status = GamelistStorage.getGame(game).gameStatus;
                    if (status == 0) {
                        File g = new File(GamelistStorage.getGame(game).gameAbsoluteFolderPath);
                        File tp = new File(Shared.workingDirectory + Shared.torrentStoreSubDirectory + "\\"
                                + GamelistStorage.getGame(game).gameName + ".torrent");
                        try {
                            MainFrame.setReportingActive();
                            TOTorrent t = TrackerManager.createNewTorrent(g, tp,
                                    new HashingProgressListener(game));
                            TrackerManager.getCore().addTorrentToTracker(t, tp.getAbsolutePath(),
                                    g.getAbsolutePath());
                            GamelistStorage.getGame(game).gameStatus = 1;
                            MainFrame.setReportingIdle();
                        } catch (Exception ex) {
                            l.error("Torrent create failed: " + game, ex);
                        }
                    } else if (status == 1 || status == 2) {
                        l.error("Game torrent already created");
                    } else if (status == 4) {
                        TrackerManager.getCore()
                                .resumeTorrentSeeding(GamelistStorage.getGame(game).gameTorrent);
                        TrackerManager.getCore()
                                .resumeTorrentTracking(GamelistStorage.getGame(game).gameTorrent);
                    } else {
                        l.error("Game has been started already");
                    }
                    return null;
                }

                @Override
                public void done() {
                    MainFrame.updateProgressBar(-1, 0, 100000, "Idle", true, true);
                    MainFrame.updateProgressBar(-1, 0, 100000, "Idle", false, true);
                    MainFrame.updateTask("Idle...", true);
                    MainFrame.unlockInterface();
                }
            };
            worker.execute();
        }
    });
    popupMenu.add(menuItem);
    JMenuItem menuItem2 = new JMenuItem("Stop");
    menuItem2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            SwingWorker worker = new SwingWorker<Void, Void>() {

                @Override
                public Void doInBackground() {
                    MainFrame.lockInterface();
                    l.trace(e.paramString());
                    int row = jTable1
                            .rowAtPoint(new Point(Shared.guiLastTablePopupX, Shared.guiLastTablePopupY));
                    String game = (String) jTable1.getModel().getValueAt(row, 0);
                    l.trace("Popup stop action! row: " + row + " and name " + game);
                    Game g = GamelistStorage.getGame(game);
                    int status = g.gameStatus;
                    if (status == 3) {
                        try {
                            TrackerManager.getCore()
                                    .pauseTorrentSeeding(GamelistStorage.getGame(game).gameTorrent);
                            TrackerManager.getCore()
                                    .pauseTorrentTracking(GamelistStorage.getGame(game).gameTorrent);
                            g.gameStatus = 4;
                        } catch (Exception ex) {
                            l.error("Torrent create failed: " + game, ex);
                        }
                    } else if (status == 1 || status == 2) {
                        l.error("Game torrent already created");
                    } else {
                        l.error("Game has been started already");
                    }
                    return null;
                }

                @Override
                public void done() {
                    MainFrame.updateProgressBar(-1, 0, 100000, "Idle", true, true);
                    MainFrame.updateProgressBar(-1, 0, 100000, "Idle", false, true);
                    MainFrame.updateTask("Idle...", true);
                    MainFrame.unlockInterface();
                }
            };
            worker.execute();
        }
    });
    //menuItem.addActionListener(new ActionAdapter(this));
    popupMenu.add(menuItem2);
    MouseListener popupListener = new PopupListener();
    jTable1.addMouseListener(popupListener);

}

From source file:com.clough.android.adbv.view.MainFrame.java

private synchronized boolean processResult(final boolean forTextOutput) {
    try {/*  w ww  .j a  v  a  2  s.c  om*/
        final JSONArray jsonArray = new JSONArray(outputResult);
        final int jsonObjectLength = jsonArray.length();

        if (jsonObjectLength > 0) {
            new SwingWorker<Void, Void>() {

                boolean columnsFound = false;

                List<String> tableColumnList = null;
                List<Integer> tableColumnWidthList = null;
                List<List<String>> tableRowList = null;

                @Override
                protected Void doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    }

                    if (forTextOutput) {
                        tableColumnList = new ArrayList<String>();
                        tableColumnWidthList = new ArrayList<Integer>();
                        tableRowList = new ArrayList<List<String>>();
                    }

                    for (int i = 0; i < jsonObjectLength; i++) {
                        waitingDialog.incrementProgressBar();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        if (!columnsFound) {

                            if (forTextOutput) {
                                tableColumnList.add("#");
                                tableColumnWidthList.add(1);
                            } else {
                                defaultTableModel.addColumn("#");
                            }

                            JSONArray fieldNamesJSONArray = jsonObject.names();
                            for (int j = 0; j < fieldNamesJSONArray.length(); j++) {
                                final String columnName = fieldNamesJSONArray.getString(j);
                                if (forTextOutput) {
                                    tableColumnList.add(columnName);
                                    tableColumnWidthList.add(columnName.length());
                                } else {
                                    defaultTableModel.addColumn(columnName);
                                }
                            }
                            columnsFound = true;
                        }

                        String rowIndex = String.valueOf(i);

                        List<String> singleRowItemList = null;
                        Object[] rowData = null;
                        if (forTextOutput) {
                            singleRowItemList = new ArrayList<String>();
                            singleRowItemList.add(rowIndex);
                            if (tableColumnWidthList.get(0) < rowIndex.length()) {
                                tableColumnWidthList.set(0, rowIndex.length());
                            }
                        } else {
                            rowData = new Object[defaultTableModel.getColumnCount()];
                            rowData[0] = rowIndex;
                        }
                        int columnLength = (forTextOutput ? tableColumnList.size()
                                : resultTable.getColumnCount());
                        for (int j = 1; j < columnLength; j++) {
                            String columnValue = (forTextOutput ? tableColumnList.get(j)
                                    : resultTable.getColumnName(j));
                            String cellValue = String.valueOf(jsonObject.get(columnValue)).replaceAll("\n", "")
                                    .replaceAll("\t", " ");
                            if (forTextOutput) {
                                singleRowItemList.add(cellValue);
                                if (tableColumnWidthList.get(j) < cellValue.length()) {
                                    tableColumnWidthList.set(j, cellValue.length());
                                }
                            } else {
                                rowData[j] = cellValue;
                            }
                        }

                        if (forTextOutput) {
                            tableRowList.add(singleRowItemList);
                        } else {
                            defaultTableModel.addRow(rowData);
                        }

                    }

                    return null;
                }

                @Override
                protected void done() {
                    closeProgressDialog();
                    if (forTextOutput) {
                        if (tableColumnList.isEmpty() || tableRowList.isEmpty()
                                || tableColumnWidthList.isEmpty()) {
                            JOptionPane.showMessageDialog(null, "No result found", "Tabular output",
                                    JOptionPane.WARNING_MESSAGE);
                        } else {
                            new SwingWorker<Void, Void>() {

                                @Override
                                protected Void doInBackground() throws Exception {
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException ex) {
                                    }
                                    int boardWidth = 0;
                                    for (Integer tableColumnWidthList1 : tableColumnWidthList) {
                                        boardWidth += tableColumnWidthList1;
                                    }
                                    boardWidth += tableColumnList.size() + 1;
                                    Board board = new Board(boardWidth);
                                    outputResultAsTextTable = board
                                            .setInitialBlock(new Table(board, boardWidth, tableColumnList,
                                                    tableRowList, tableColumnWidthList).tableToBlocks())
                                            .getPreview();
                                    return null;
                                }

                                @Override
                                protected void done() {
                                    closeProgressDialog();
                                }

                            }.execute();
                            showProgressDialog(true, 0, "Creating table for " + jsonObjectLength + " fields");
                        }
                    } else {
                        tableColumnAdjuster.adjustColumns();
                    }
                }

            }.execute();
            showProgressDialog(false, jsonObjectLength, "Processing " + jsonObjectLength + " fields");
            return false;
        } else {
            return true;
        }
    } catch (JSONException ex) {
        JOptionPane.showMessageDialog(null, outputResult, "Result error", JOptionPane.ERROR_MESSAGE);
        return true;
    }
}

From source file:com.puzzle.gui.MainFrame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    // TODO add your handling code here:

    String comboxValue = (String) jComboBox1.getSelectedItem();
    if (StringUtils.isBlank(comboxValue) || "?...".equals(comboxValue)) {
        JOptionPane.showMessageDialog(this, "?");

        //             JOptionPane.showMessageDialog(this, evt);
        return;//from   w w  w .jav  a2s. c  o  m

    }

    int returnVal = jFileChooser1.showOpenDialog(this);
    if (returnVal == jFileChooser1.APPROVE_OPTION) {
        String fileName = jFileChooser1.getSelectedFile().getAbsolutePath();
        if (StringUtils.isBlank(fileName)) {
            return;
        }

        log.info("" + fileName);
        jTextField5.setText(fileName);
        jTextField5.setToolTipText(fileName);

        FileDto.getSingleInstance().fileName = fileName;

        if (fileName == null || fileName.trim().equals("")) {
            log.info("");
            return;
        }

        FileDto.getSingleInstance().type = convertStr(comboxValue);
        if (StringUtils.isBlank(FileDto.getSingleInstance().type)) {
            return;
        }
        FileDto.getSingleInstance().reloadConfi(fileName, FileDto.getSingleInstance().type);

        //            jDialog2.setLocationRelativeTo(this);
        //            jDialog2.setVisible(true);

        //            new UkeyC().run();

        new SwingWorker<String, Void>() {

            @Override
            protected String doInBackground() throws Exception {
                jLabel6.setVisible(true);
                jComboBox1.setEnabled(false);
                jButton8.setEnabled(false);

                new UkeyC().run();

                return "1";//??
            }

            @Override
            protected void done() {
                jLabel6.setVisible(false);

                if (UkeyLoginDto.islogin) {
                    startSendAndReceDirectoryMonitor.startMonitor();
                    jButton8.setEnabled(false);
                    jComboBox1.setEnabled(false);
                }

            }
        }.execute();

        //                   if (UkeyLoginDto.islogin) {
        //                startSendAndReceDirectoryMonitor.startMonitor();
        //                jButton8.setEnabled(false);
        //            }

        //            jDialog2.setVisible(false);
        //            jComboBox1.setEnabled(false);
    }
}

From source file:com.xilinx.kintex7.MainScreen.java

private JPanel testPanelItems() {
    JPanel panel1 = new JPanel();

    JPanel panel = new JPanel();

    panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

    panel.add(new JLabel("Data Path-0:"));
    t1_o1 = new JCheckBox("Loopback");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t1_o1.setToolTipText("This loops back software generated traffic at DMA user interface");
    else if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV)
        t1_o1.setToolTipText("This loops back software generated raw Ethernet frames at 10G PHY");

    t1_o1.setSelected(true);//from ww  w  .  j ava 2 s . c o m
    t1_o1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
                t1_o1.setSelected(true);
                return;
            }
            if (t1_o1.isSelected()) {
                // disable others
                test1_option = DriverInfo.ENABLE_LOOPBACK;
                t1_o2.setSelected(false);
                t1_o3.setSelected(false);
            } else {
                if (!t1_o2.isSelected() && !t1_o3.isSelected()) {
                    test1_option = DriverInfo.CHECKER;
                    t1_o2.setSelected(true);
                }
            }
        }
    });
    //b1.setSelected(true);
    t1_o2 = new JCheckBox("HW Checker");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t1_o2.setToolTipText(
                "This enables Checker in hardware at DMA user interface verifying traffic generated by software");
    t1_o2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (t1_o2.isSelected()) {
                // disable others
                test1_option = DriverInfo.CHECKER;
                t1_o1.setSelected(false);
                if (t1_o3.isSelected())
                    test1_option = DriverInfo.CHECKER_GEN;
            } else {
                if (t1_o3.isSelected())
                    test1_option = DriverInfo.GENERATOR;
                else {
                    test1_option = DriverInfo.ENABLE_LOOPBACK;
                    t1_o1.setSelected(true);
                }

            }
        }
    });
    t1_o3 = new JCheckBox("HW Generator");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t1_o3.setToolTipText("This enables traffic generator in hardware at the DMA user interface");
    t1_o3.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (t1_o3.isSelected()) {
                // disable others
                test1_option = DriverInfo.GENERATOR;
                t1_o1.setSelected(false);
                //t1_o2.setSelected(false);
                if (t1_o2.isSelected())
                    test1_option = DriverInfo.CHECKER_GEN;
            } else {
                if (t1_o2.isSelected())
                    test1_option = DriverInfo.CHECKER;
                else {
                    test1_option = DriverInfo.ENABLE_LOOPBACK;
                    t1_o1.setSelected(true);
                }
            }
        }
    });
    //b3.setEnabled(false);
    JPanel ip = new JPanel();
    ip.setLayout(new BoxLayout(ip, BoxLayout.PAGE_AXIS));
    ip.add(t1_o1);
    ip.add(t1_o2);
    ip.add(t1_o3);
    panel.add(ip);
    panel.add(new JLabel("Packet Size (bytes):"));
    t1_psize = new JTextField("32768", 5);

    panel.add(t1_psize);
    startTest = new JButton("Start");
    startTest.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {

            //Check for led status and start the test
            if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
                if (lstats.ddrCalib == LED_OFF && (lstats.phy0 == LED_ON && lstats.phy1 == LED_ON)) {
                    JOptionPane.showMessageDialog(null, "DDR3 is not calibrated. Test cannot be started",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                } else if (lstats.ddrCalib == LED_OFF && (lstats.phy0 == LED_OFF || lstats.phy1 == LED_OFF)) {
                    JOptionPane.showMessageDialog(null,
                            "DDR3 is not calibrated and 10G-PHY link is down. Test cannot be started", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                } else if (lstats.ddrCalib == LED_ON && (lstats.phy0 == LED_OFF || lstats.phy1 == LED_OFF)) {
                    JOptionPane.showMessageDialog(null, "10G-PHY link is down. Test cannot be started", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }

            if (startTest.getText().equals("Start")) {
                int psize = 0;
                dataMismatch0 = errcnt0 = false;
                try {
                    psize = Integer.parseInt(t1_psize.getText());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Only Natural numbers are allowed", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (psize < minpkt0 || psize > maxpkt0) {
                    JOptionPane.showMessageDialog(null,
                            "Packet size must be within " + minpkt0 + " to " + maxpkt0 + " bytes", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                di.startTest(0, test1_option, psize);
                // disable components
                t1_o1.setEnabled(false);
                t1_o2.setEnabled(false);
                t1_o3.setEnabled(false);
                t1_psize.setEnabled(false);
                startTest.setText("Stop");
                testStarted = true;
                updateLog("[Test Started for Data Path-0]", logStatus);
            } else if (startTest.getText().equals("Stop")) {
                startTest.setEnabled(false);
                SwingWorker worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        try {
                            stopTest1();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                };
                worker.execute();
            }
        }
    });
    panel.add(startTest);
    if ((mode == LandingPage.APPLICATION_MODE) || (mode == LandingPage.APPLICATION_MODE_P2P)) {
        t1_o1.setSelected(false);
        t1_o2.setSelected(false);
        t1_o3.setSelected(false);
        t1_o1.setEnabled(false);
        t1_o2.setEnabled(false);
        t1_o3.setEnabled(false);
        t1_psize.setEnabled(false);
        t1_psize.setText("");
        startTest.setEnabled(false);
    }
    panel1.add(panel);
    return panel1;
}