Example usage for javax.swing JDialog JDialog

List of usage examples for javax.swing JDialog JDialog

Introduction

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

Prototype

public JDialog(Window owner) 

Source Link

Document

Creates a modeless dialog with the specified Window as its owner and an empty title.

Usage

From source file:com.sciaps.view.SpectrumAnalysisReportPanel.java

public void doAnalysis(final SpectrumShotItem spectrumShotItem) {
    logger_.info("Starting Spectrum Analysis");

    spectrumShotItem_ = spectrumShotItem;

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override//from w ww  . j  a v a  2 s  . co  m
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {

            Spectrum tmp = null;
            final double[] peaksOnX_;

            if (spectrumShotItem.getSeriesDataType() == SpectrumShotItem.NORMALIZED) {
                tmp = spectrumShotItem.getShot();
                peaksOnX_ = spectrumAnalyze_.doPeakFinding(tmp);
            } else if (spectrumShotItem.getSeriesDataType() == SpectrumShotItem.BG_REMOVED) {

                tmp = spectrumAnalyze_.doSpectrumNormalization(spectrumShotItem.getShot());
                peaksOnX_ = spectrumAnalyze_.doPeakFinding(tmp);
            } else {

                tmp = spectrumAnalyze_.doBackgroundRemoval(spectrumShotItem.getShot());
                tmp = spectrumAnalyze_.doSpectrumNormalization(tmp);
                peaksOnX_ = spectrumAnalyze_.doPeakFinding(tmp);
            }

            // Create a marker for each peaks and show them
            if (peaksOnX_.length > 0) {

                normalizedSpectrumItem_ = new SpectrumShotItem("analysis");
                normalizedSpectrumItem_.setShot(tmp, SpectrumShotItem.NORMALIZED);

                final HashMap<String, PeakMeritObj> mapOfPeaks = new HashMap<String, PeakMeritObj>();

                // Merge all the identified peak into one object
                // this for loop will set the found value
                for (int i = 0; i < peaksOnX_.length; i++) {
                    double y = tmp.getIntensityFunction().value(peaksOnX_[i]);

                    PeakMeritObj retMeritObj = spectrumAnalyze_.identifiedPeaks(peaksOnX_[i], y, searchRange_);
                    if (retMeritObj != null) {
                        PeakMeritObj meritObjInTheMap = mapOfPeaks.get(retMeritObj.elementName_);
                        if (meritObjInTheMap == null) {
                            // not in the list, add it
                            mapOfPeaks.put(retMeritObj.elementName_, retMeritObj);
                        } else {
                            // in the list already, update it
                            meritObjInTheMap.addWavelength(retMeritObj.getWaveLength());
                            meritObjInTheMap.addTotalPeaksFound(retMeritObj.getTotalPeaksFound());
                            meritObjInTheMap.addTotalLgPeaksFound(retMeritObj.getTotalLgPeaksFound());
                            meritObjInTheMap.addWeight(retMeritObj.getWeight());
                            meritObjInTheMap.addMerit(retMeritObj.getMerit());
                        }
                    }
                }

                //Now we have a list of identified peaks, going to get the element info on the libzlines library
                for (PeakMeritObj obj : mapOfPeaks.values()) {
                    spectrumAnalyze_.getElementLineData(obj);
                }

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {

                        // Remove all previous data
                        listModel_.removeAllElements();
                        lblSpectrumName_.setText(spectrumShotItem.getName());
                        markers_ = null;
                        peakMeritTableModel_.clearAllData();
                        rejectedPeakMeritTableModel_.clearAllData();

                        callback_.doShowShotXYSeries(normalizedSpectrumItem_);

                        int offset = -1;
                        IntervalMarker[] tmpMarkers = new IntervalMarker[peaksOnX_.length];
                        double min;
                        double max;
                        double tmpPeakFoundPercentage;
                        double tmpLgPeakFoundPercentage;
                        double tmpPeakWeightPercentage;
                        for (PeakMeritObj obj : mapOfPeaks.values()) {
                            for (Object wl : obj.getWaveLength()) {
                                String item = String.format("%.5g, %s", wl, obj.elementName_);
                                listModel_.addElement(item);

                                min = (Double) wl - MARKER_THRESHOLD;
                                max = (Double) wl + MARKER_THRESHOLD;
                                IntervalMarker marker = Util.createMarker(min, max, obj.elementName_);
                                tmpMarkers[++offset] = marker;
                            }

                            if (obj.getTotalLgPeaks() > 0) {
                                tmpPeakFoundPercentage = 100f * obj.getTotalPeaksFound() / obj.getTotalPeaks();
                                tmpLgPeakFoundPercentage = 100f * obj.getTotalLgPeaksFound()
                                        / obj.getTotalLgPeaks();

                            } else {
                                tmpPeakFoundPercentage = 0;
                                tmpLgPeakFoundPercentage = 0;
                            }
                            tmpPeakWeightPercentage = obj.getWeightPercentage();

                            // determine peak accept/reject
                            if (tmpPeakFoundPercentage >= peakFoundPercentage_
                                    && tmpLgPeakFoundPercentage >= lgPeakFoundPercentage_
                                    && tmpPeakWeightPercentage >= peakWeightPercentage_) {
                                peakMeritTableModel_.addRow(obj);
                            } else {
                                rejectedPeakMeritTableModel_.addRow(obj);
                            }
                        }

                        allMarkers_ = Arrays.copyOf(tmpMarkers, offset + 1);
                        callback_.doAddMarker(allMarkers_);
                    }
                });
            }
        }

        @Override
        public void onAfter() {
            mDialog.setVisible(false);
            logger_.info("Spectrum Analysis - done");
        }
    });

}

From source file:net.cantab.hayward.george.OCS.Statics.java

/**
 * Create the normal toolbar entries/*from ww  w  .  jav  a 2  s. c o  m*/
 */
void createNormalEntries() {
    commandLaunch = new JButton("Command...");
    commandLaunch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            launchCommandMenu();
        }
    });
    commandLaunch.setFocusable(false);
    commandLaunch.setToolTipText("Take/Resign command of a side");
    toolbar.add(commandLaunch);
    instructions = new JButton("Scenario Notes");
    instructions.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            displayInstructions();
        }
    });
    instructions.setFocusable(false);
    toolbar.add(instructions);
    /*
     * If in edit mode add option to process pieces to OCS module form quickly
     */
    if (GameModule.getGameModule().getArchiveWriter() != null) {
        piecesLaunch = new JButton("Piece Definitions");
        piecesLaunch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                piecesProcess();
            }
        });
        piecesLaunch.setFocusable(false);
        toolbar.add(piecesLaunch);
        piecesWindow = new JDialog(GameModule.getGameModule().getFrame());
        piecesWindow.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        piecesWindow.setTitle("Piece definitions");
        piecesWindow.setSize(700, 500);
        piecesWindow.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                piecesWindow.setVisible(false);
            }
        });
        piecesWindow.add(new PieceProcessor());
        textLaunch = new JButton("Read Scenario from Text File");
        textLaunch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                readTextFile();
            }
        });
        textLaunch.setFocusable(false);
        textLaunch.setEnabled(false);
        toolbar.add(textLaunch);
        createPieces = new JButton("Create Pieces from file");
        createPieces.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                createPiecesFromFile();
            }
        });
        createPieces.setFocusable(false);
        createPieces.setEnabled(true);
        toolbar.add(createPieces);
        checkOrder = new JButton("Check Layers/Mask Order");
        checkOrder.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                checkLayerOrders();
            }
        });
        checkOrder.setFocusable(false);
        checkOrder.setEnabled(true);
        toolbar.add(checkOrder);
    }
}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void doCreateAvg() {

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override//from w  ww .ja  va2s .co  m
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    logger_.info("Creating avg from highlighted shots...");

                    StringBuilder name = new StringBuilder();

                    boolean gotScanID = false;
                    int[] selectedList = tblShots_.getSelectedRows();
                    List<Spectrum> shotDatas = new ArrayList<Spectrum>();

                    for (int i = 0; i < selectedList.length; i++) {
                        int modelIndex = tblShots_.convertRowIndexToModel(selectedList[i]);
                        SpectrumShotItem shotItem = (SpectrumShotItem) shotListTableModel_.getRow(modelIndex);
                        if (gotScanID == false) {
                            name.append("Scan ").append(shotItem.getScanID()).append(" Avg: ");
                            gotScanID = true;
                        }
                        name.append(shotItem.getShotID());
                        name.append("_");

                        shotDatas.add(shotItem.getShot());
                    }
                    name = name.deleteCharAt(name.length() - 1);

                    AverageShotsSettingPanel avgPanel = new AverageShotsSettingPanel();
                    avgPanel.setAvgShotName(name.toString());
                    int sampleRate = validateOneOrGreater(txtSampleRate_);
                    if (sampleRate >= 1) {
                        avgPanel.setSampleRate(sampleRate);
                    } else {
                        avgPanel.setSampleRate(30);
                    }

                    CustomDialog dialog = new CustomDialog(Constants.MAIN_FRAME, "Shot Average Setting",
                            avgPanel, CustomDialog.OK_OPTION);
                    dialog.setSize(400, 200);
                    dialog.setVisible(true);

                    int retval = dialog.getResponseValue();
                    String newName = avgPanel.getAvgShotName();
                    while (retval == CustomDialog.OK && shotListTableModel_.isNameAlreadyExist(newName)) {
                        avgPanel.doNameAlreadyExist(true);
                        dialog.setVisible(true);
                        retval = dialog.getResponseValue();
                        newName = avgPanel.getAvgShotName();
                    }

                    if (retval == CustomDialog.OK) {
                        int newSampleRate = avgPanel.getSampleRate();

                        final SpectrumShotItem newShotItem = new SpectrumShotItem(newName.replace(",", "_"));
                        newShotItem.setShot(createAverage(shotDatas, newSampleRate), SpectrumShotItem.AVERAGED);

                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                shotListTableModel_.addRow(0, newShotItem);
                                shotListTableModel_.setValueAt(true, 0, 0); //display it

                            }
                        });

                        logger_.info("Create Avg from highlighted shots.... done");
                    } else {
                        logger_.info("Create Avg aborted by user");
                    }
                }

            });
        }

        @Override

        public void onAfter() {
            mDialog.setVisible(false);
        }
    });
}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void doBackgroundRemoval() {

    final int[] selectedRow = getSelectedRows();
    if (selectedRow == null || selectedRow.length == 0) {
        return;//from w w  w  . j  a  v a 2s.c o  m
    }

    final double stepSize = baselineSettingPanel_.getStepSize();
    final double wlInterval = baselineSettingPanel_.getWaveLengthInterval();

    if (stepSize < 0 || wlInterval < 0) {
        return;
    }

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {

            final ArrayList<SpectrumShotItem> tmpList = new ArrayList<SpectrumShotItem>();
            final StringBuilder errMsg = new StringBuilder();

            for (int rowIndex = 0; rowIndex < selectedRow.length; rowIndex++) {
                String name = shotListTableModel_.getRow(selectedRow[rowIndex]).getName();
                name = name + "R" + stepSize + "_" + wlInterval;

                if (shotListTableModel_.isNameAlreadyExist(name) == false) {
                    Spectrum spectrum = shotListTableModel_.getRow(selectedRow[rowIndex]).getShot();

                    RawDataSpectrum rawSpect = doBackgroundRemoval(spectrum);

                    if (rawSpect != null) {
                        SpectrumShotItem shot = new SpectrumShotItem(name);
                        shot.setShot(rawSpect, SpectrumShotItem.BG_REMOVED);

                        tmpList.add(shot);
                    } else {
                        errMsg.append(name).append("\n");
                    }
                } else {
                    errMsg.append(name).append("\n");
                }
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    for (SpectrumShotItem shot : tmpList) {
                        shotListTableModel_.addRow(0, shot);
                    }

                    if (tmpList.isEmpty() == false) {
                        shotListTableModel_.showSeries(0);
                    }

                    if (errMsg.length() > 0) {
                        errMsg.insert(0, "The following shot(s) already exist, skipped:\n");
                        showErrorDialog(errMsg.toString());
                    }

                }
            });

        }

        @Override
        public void onAfter() {
            mDialog.setVisible(false);
        }
    });

}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void doSpectrumNormalization() {

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override/*  w  w  w  .  j  a  v a2  s. c  o m*/
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {

            int[] selectedRow = getSelectedRows();
            if (selectedRow == null || selectedRow.length == 0) {
                return;
            }

            final ArrayList<SpectrumShotItem> tmpList = new ArrayList<SpectrumShotItem>();
            final StringBuilder errMsg = new StringBuilder();

            SpectrumNormalization spectrumNormalization = new SpectrumNormalization();
            for (int rowIndex = 0; rowIndex < selectedRow.length; rowIndex++) {
                SpectrumShotItem selectedItem = shotListTableModel_.getRow(selectedRow[rowIndex]);

                String name = selectedItem.getName();
                name = name + "N";

                if (selectedItem.getSeriesDataType() != SpectrumShotItem.NORMALIZED) {

                    Spectrum normalizedSpectrum = null;
                    if (selectedItem.getSeriesDataType() == SpectrumShotItem.BG_REMOVED) {
                        normalizedSpectrum = spectrumNormalization
                                .normalize((RawDataSpectrum) selectedItem.getShot());
                    } else {
                        RawDataSpectrum tempSpectrum = doBackgroundRemoval(selectedItem.getShot());
                        normalizedSpectrum = doSpectrumNormalization(tempSpectrum);
                    }

                    if (normalizedSpectrum != null) {
                        SpectrumShotItem shotItem = new SpectrumShotItem(name);
                        shotItem.setShot(normalizedSpectrum, SpectrumShotItem.NORMALIZED);
                        tmpList.add(shotItem);
                    } else {
                        errMsg.append(name).append("\n");
                    }

                } else {
                    errMsg.append(name).append("\n");
                }
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    for (SpectrumShotItem shot : tmpList) {
                        shotListTableModel_.addRow(0, shot);
                    }

                    if (tmpList.isEmpty() == false) {
                        shotListTableModel_.showSeries(0);
                    }

                    if (errMsg.length() > 0) {
                        errMsg.insert(0, "The following shot(s) already exist, skipped:\n");
                        showErrorDialog(errMsg.toString());
                    }

                }
            });

        }

        @Override
        public void onAfter() {
            mDialog.setVisible(false);
        }
    });
}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void doFindPeak() {

    final int[] selectedRows = tblShots_.getSelectedRows();
    if (selectedRows == null || selectedRows.length == 0) {
        showErrorDialog("No spectrum is selected to find peak on.");
        return;/*from   w w  w  .  jav a  2s  .c om*/
    }

    if (selectedRows.length != 1) {
        showErrorDialog("Select 1 spectrum to continue.");
        return;
    }

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {
            StringBuilder errMsg = new StringBuilder();

            SpectrumPeakFinding peakFinding = new SpectrumPeakFinding(30);

            int modelIndex = tblShots_.convertRowIndexToModel(selectedRows[0]);
            final SpectrumShotItem selectedItem = shotListTableModel_.getRow(modelIndex);
            final double[] peaksOnX;

            if (selectedItem.getSeriesDataType() == SpectrumShotItem.NORMALIZED) {

                peaksOnX = peakFinding.getPeaks(selectedItem.getShot());
            } else if (selectedItem.getSeriesDataType() == SpectrumShotItem.BG_REMOVED) {

                RawDataSpectrum tmp = doSpectrumNormalization((RawDataSpectrum) selectedItem.getShot());
                peaksOnX = peakFinding.getPeaks(tmp);
            } else {

                RawDataSpectrum tmp = doBackgroundRemoval(selectedItem.getShot());
                tmp = doSpectrumNormalization(tmp);
                peaksOnX = peakFinding.getPeaks(tmp);
            }

            if (peaksOnX.length > 0) {

                peakMarkers_ = new IntervalMarker[peaksOnX.length];
                double min;
                double max;
                for (int i = 0; i < peaksOnX.length; i++) {

                    min = peaksOnX[i] - MARKER_THRESHOLD;
                    max = peaksOnX[i] + MARKER_THRESHOLD;
                    IntervalMarker marker = Util.createMarker(min, max);
                    peakMarkers_[i] = marker;
                }

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {

                        // unselected all other series
                        tblShots_.selectAll();
                        SpectrumShotItem tmpItem;
                        for (int i : tblShots_.getSelectedRows()) {
                            tmpItem = shotListTableModel_.getRow(i);
                            tmpItem.setSelected(false);
                            callback_.doDeleteShotXYSeries(tmpItem);
                        }

                        shotListTableModel_.showSeries(selectedRows[0]);
                        tblShots_.setRowSelectionInterval(selectedRows[0], selectedRows[0]);
                        callback_.doAddMarker(peakMarkers_);
                    }
                });
            }
        }

        @Override
        public void onAfter() {
            mDialog.setVisible(false);
        }

    });
}

From source file:userinterface.properties.GUIGraphHandler.java

public void plotNewFunction() {

    JDialog dialog;/*ww w.  j ava2 s. c o m*/
    JRadioButton radio2d, radio3d, newGraph, existingGraph;
    JTextField functionField, seriesName;
    JButton ok, cancel;
    JComboBox<String> chartOptions;
    JLabel example;

    //init all the fields of the dialog
    dialog = new JDialog(GUIPrism.getGUI());
    radio2d = new JRadioButton("2D");
    radio3d = new JRadioButton("3D");
    newGraph = new JRadioButton("New Graph");
    existingGraph = new JRadioButton("Exisiting");
    chartOptions = new JComboBox<String>();
    functionField = new JTextField();
    ok = new JButton("Plot");
    cancel = new JButton("Cancel");
    seriesName = new JTextField();
    example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
    example.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.HAND_CURSOR));
            example.setForeground(Color.BLUE);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            example.setForeground(Color.BLACK);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getButton() == MouseEvent.BUTTON1) {

                if (radio2d.isSelected()) {
                    functionField.setText("x/2 + 5");
                } else {
                    functionField.setText("x+y+5");
                }

                functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
                functionField.setForeground(Color.BLACK);

            }
        }

    });

    //set dialog properties
    dialog.setSize(400, 350);
    dialog.setTitle("Plot a new function");
    dialog.setModal(true);
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setLocationRelativeTo(GUIPrism.getGUI());

    //add every component to their dedicated panels
    JPanel graphTypePanel = new JPanel(new FlowLayout());
    graphTypePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type"));
    graphTypePanel.add(radio2d);
    graphTypePanel.add(radio3d);

    JPanel functionFieldPanel = new JPanel(new BorderLayout());
    functionFieldPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function"));
    functionFieldPanel.add(functionField, BorderLayout.CENTER);
    functionFieldPanel.add(example, BorderLayout.SOUTH);

    JPanel chartSelectPanel = new JPanel();
    chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS));
    chartSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to"));
    JPanel radioPlotPanel = new JPanel(new FlowLayout());
    radioPlotPanel.add(newGraph);
    radioPlotPanel.add(existingGraph);
    JPanel chartOptionsPanel = new JPanel(new FlowLayout());
    chartOptionsPanel.add(chartOptions);
    chartSelectPanel.add(radioPlotPanel);
    chartSelectPanel.add(chartOptionsPanel);

    JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomControlPanel.add(ok);
    bottomControlPanel.add(cancel);

    JPanel seriesNamePanel = new JPanel(new BorderLayout());
    seriesNamePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name"));
    seriesNamePanel.add(seriesName, BorderLayout.CENTER);

    // add all the panels to the dialog

    dialog.add(graphTypePanel);
    dialog.add(functionFieldPanel);
    dialog.add(chartSelectPanel);
    dialog.add(seriesNamePanel);
    dialog.add(bottomControlPanel);

    // do all the enables and set properties

    radio2d.setSelected(true);
    newGraph.setSelected(true);
    chartOptions.setEnabled(false);
    functionField.setText("Add function expression here....");
    functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
    functionField.setForeground(Color.GRAY);
    seriesName.setText("New function");
    ok.setMnemonic('P');
    cancel.setMnemonic('C');
    example.setToolTipText("click to try out");

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    boolean found = false;

    for (int i = 0; i < theTabs.getTabCount(); i++) {

        if (theTabs.getComponentAt(i) instanceof Graph) {
            chartOptions.addItem(getGraphName(i));
            found = true;
        }
    }

    if (!found) {

        existingGraph.setEnabled(false);
        chartOptions.setEnabled(false);
    }

    //add all the action listeners

    radio2d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio2d.isSelected()) {

                radio3d.setSelected(false);

                if (chartOptions.getItemCount() > 0) {
                    existingGraph.setEnabled(true);
                    chartOptions.setEnabled(true);
                }

                example.setText(
                        "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
            }
        }
    });

    radio3d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio3d.isSelected()) {

                radio2d.setSelected(false);
                newGraph.setSelected(true);
                existingGraph.setEnabled(false);
                chartOptions.setEnabled(false);
                example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>");

            }

        }
    });

    newGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (newGraph.isSelected()) {
                existingGraph.setSelected(false);
                chartOptions.setEnabled(false);
            }
        }
    });

    existingGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existingGraph.isSelected()) {

                newGraph.setSelected(false);
                chartOptions.setEnabled(true);
            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String function = functionField.getText();

            Expression expr = null;

            try {

                expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function);
                expr = (Expression) expr.accept(new ASTTraverseModify() {

                    @Override
                    public Object visit(ExpressionIdent e) throws PrismLangException {
                        return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                    }

                });

                expr.typeCheck();
                expr.semanticCheck();

            } catch (PrismLangException e1) {

                // for copying style
                JLabel label = new JLabel();

                // html content in our case the error we want to show
                JEditorPane ep = new JEditorPane("text/html",
                        "<html> There was an error parsing the function. To read about what built-in"
                                + " functions are supported <br>and some more information on the functions, visit "
                                + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>."
                                + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>");

                // handle link events
                ep.addHyperlinkListener(new HyperlinkListener() {
                    @Override
                    public void hyperlinkUpdate(HyperlinkEvent e) {
                        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                            try {
                                Desktop.getDesktop().browse(e.getURL().toURI());
                            } catch (IOException | URISyntaxException e1) {

                                e1.printStackTrace();
                            }
                        }
                    }
                });
                ep.setEditable(false);
                ep.setBackground(label.getBackground());

                // show the error dialog
                JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (radio2d.isSelected()) {

                ParametricGraph graph = null;

                if (newGraph.isSelected()) {

                    graph = new ParametricGraph("");
                } else {

                    for (int i = 0; i < theTabs.getComponentCount(); i++) {

                        if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) {

                            graph = (ParametricGraph) theTabs.getComponent(i);
                        }
                    }

                }

                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true);

            } else if (radio3d.isSelected()) {

                try {

                    expr = (Expression) expr.accept(new ASTTraverseModify() {
                        @Override
                        public Object visit(ExpressionIdent e) throws PrismLangException {
                            return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                        }

                    });

                    expr.semanticCheck();
                    expr.typeCheck();

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

                if (expr.getAllConstants().size() < 2) {

                    JOptionPane.showMessageDialog(dialog,
                            "There are not enough variables in the function to plot a 3D chart!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // its always a new graph
                ParametricGraph3D graph = new ParametricGraph3D(expr);
                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false);
            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    // we will show info about the function when field is out of focus
    functionField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {

            if (!functionField.getText().equals("")) {
                return;
            }

            functionField.setText("Add function expression here....");
            functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
            functionField.setForeground(Color.GRAY);
        }

        @Override
        public void focusGained(FocusEvent e) {

            if (!functionField.getText().equals("Add function expression here....")) {
                return;
            }

            functionField.setForeground(Color.BLACK);
            functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
            functionField.setText("");
        }
    });

    // show the dialog
    dialog.setVisible(true);
}

From source file:userinterface.properties.GUIGraphHandler.java

public void defineConstantsAndPlot(Expression expr, JPanel graph, String seriesName, Boolean isNewGraph,
        boolean is2D) {

    JDialog dialog;/*w  w w .  j a  v  a  2s  . c o m*/
    JButton ok, cancel;
    JScrollPane scrollPane;
    ConstantPickerList constantList;
    JComboBox<String> xAxis, yAxis;

    //init everything
    dialog = new JDialog(GUIPrism.getGUI());
    dialog.setTitle("Define constants and select axes");
    dialog.setSize(500, 400);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setModal(true);

    constantList = new ConstantPickerList();
    scrollPane = new JScrollPane(constantList);

    xAxis = new JComboBox<String>();
    yAxis = new JComboBox<String>();

    ok = new JButton("Ok");
    ok.setMnemonic('O');
    cancel = new JButton("Cancel");
    cancel.setMnemonic('C');

    //add all components to their dedicated panels
    JPanel exprPanel = new JPanel(new FlowLayout());
    exprPanel.setBorder(new TitledBorder("Function"));
    exprPanel.add(new JLabel(expr.toString()));

    JPanel axisPanel = new JPanel();
    axisPanel.setBorder(new TitledBorder("Select axis constants"));
    axisPanel.setLayout(new BoxLayout(axisPanel, BoxLayout.Y_AXIS));
    JPanel xAxisPanel = new JPanel(new FlowLayout());
    xAxisPanel.add(new JLabel("X axis:"));
    xAxisPanel.add(xAxis);
    JPanel yAxisPanel = new JPanel(new FlowLayout());
    yAxisPanel.add(new JLabel("Y axis:"));
    yAxisPanel.add(yAxis);
    axisPanel.add(xAxisPanel);
    axisPanel.add(yAxisPanel);

    JPanel constantPanel = new JPanel(new BorderLayout());
    constantPanel.setBorder(new TitledBorder("Please define the following constants"));
    constantPanel.add(scrollPane, BorderLayout.CENTER);
    constantPanel.add(new ConstantHeader(), BorderLayout.NORTH);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomPanel.add(ok);
    bottomPanel.add(cancel);

    //fill the axes components

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        xAxis.addItem(expr.getAllConstants().get(i));

        if (!is2D)
            yAxis.addItem(expr.getAllConstants().get(i));
    }

    if (!is2D) {
        yAxis.setSelectedIndex(1);
    }

    //fill the constants table

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        ConstantLine line = new ConstantLine(expr.getAllConstants().get(i), TypeDouble.getInstance());
        constantList.addConstant(line);

        if (!is2D) {
            if (line.getName().equals(xAxis.getSelectedItem().toString())
                    || line.getName().equals(yAxis.getSelectedItem().toString())) {

                line.doFuncEnables(false);
            } else {
                line.doFuncEnables(true);
            }
        }

    }

    //do enables

    if (is2D) {
        yAxis.setEnabled(false);
    }

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    //add action listeners

    xAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (is2D) {
                return;
            }

            String item = xAxis.getSelectedItem().toString();

            if (item.equals(yAxis.getSelectedItem().toString())) {

                int index = yAxis.getSelectedIndex();

                if (index != yAxis.getItemCount() - 1) {
                    yAxis.setSelectedIndex(++index);
                } else {
                    yAxis.setSelectedIndex(--index);
                }

            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    yAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String item = yAxis.getSelectedItem().toString();

            if (item.equals(xAxis.getSelectedItem().toString())) {

                int index = xAxis.getSelectedIndex();

                if (index != xAxis.getItemCount() - 1) {
                    xAxis.setSelectedIndex(++index);
                } else {
                    xAxis.setSelectedIndex(--index);
                }
            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                constantList.checkValid();

            } catch (PrismException e2) {
                JOptionPane.showMessageDialog(dialog,
                        "<html> One or more of the defined constants are invalid. <br><br> <font color=red>Error: </font>"
                                + e2.getMessage() + "</html>",
                        "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (is2D) {

                // it will always be a parametric graph in 2d case
                ParametricGraph pGraph = (ParametricGraph) graph;

                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());

                if (xAxisConstant == null) {
                    //should never happen
                    JOptionPane.showMessageDialog(dialog, "The selected axis is invalid.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double xStartValue = Double.parseDouble(xAxisConstant.getStartValue());
                double xEndValue = Double.parseDouble(xAxisConstant.getEndValue());
                double xStepValue = Double.parseDouble(xAxisConstant.getStepValue());

                int seriesCount = 0;

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getName().equals(xAxis.getSelectedItem().toString())) {
                        seriesCount++;
                    } else {

                        seriesCount += line.getTotalNumOfValues();

                    }
                }

                // if there will be too many series to be plotted, ask the user if they are sure they know what they are doing
                if (seriesCount > 10) {

                    int res = JOptionPane.showConfirmDialog(dialog,
                            "This configuration will create " + seriesCount + " series. Continue?", "Confirm",
                            JOptionPane.YES_NO_OPTION);

                    if (res == JOptionPane.NO_OPTION) {
                        return;
                    }

                }

                Values singleValuesGlobal = new Values();

                //add the single values to a global values list

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                // we just have one variable so we can plot directly
                if (constantList.getNumConstants() == 1
                        || singleValuesGlobal.getNumValues() == constantList.getNumConstants() - 1) {

                    SeriesKey key = pGraph.addSeries(seriesName);

                    pGraph.hideShape(key);
                    pGraph.getXAxisSettings().setHeading(xAxis.getSelectedItem().toString());
                    pGraph.getYAxisSettings().setHeading("function");

                    for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                        double ans = -1;

                        Values vals = new Values();
                        vals.addValue(xAxis.getSelectedItem().toString(), x);

                        for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                            try {
                                vals.addValue(singleValuesGlobal.getName(ii),
                                        singleValuesGlobal.getDoubleValue(ii));
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                        }

                        try {
                            ans = expr.evaluateDouble(vals);
                        } catch (PrismLangException e1) {
                            e1.printStackTrace();
                        }

                        pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));

                    }

                    if (isNewGraph) {
                        addGraph(pGraph);
                    }

                    dialog.dispose();
                    return;
                }

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line == xAxisConstant || singleValuesGlobal.contains(line.getName())) {
                        continue;
                    }

                    double lineStart = Double.parseDouble(line.getStartValue());
                    double lineEnd = Double.parseDouble(line.getEndValue());
                    double lineStep = Double.parseDouble(line.getStepValue());

                    for (double j = lineStart; j < lineEnd; j += lineStep) {

                        SeriesKey key = pGraph.addSeries(seriesName);
                        pGraph.hideShape(key);

                        for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                            double ans = -1;

                            Values vals = new Values();
                            vals.addValue(xAxis.getSelectedItem().toString(), x);
                            vals.addValue(line.getName(), j);

                            for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                                try {
                                    vals.addValue(singleValuesGlobal.getName(ii),
                                            singleValuesGlobal.getDoubleValue(ii));
                                } catch (PrismLangException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                            }

                            for (int ii = 0; ii < constantList.getNumConstants(); ii++) {

                                if (constantList.getConstantLine(ii) == xAxisConstant
                                        || singleValuesGlobal
                                                .contains(constantList.getConstantLine(ii).getName())
                                        || constantList.getConstantLine(ii) == line) {

                                    continue;
                                }

                                ConstantLine temp = constantList.getConstantLine(ii);
                                double val = Double.parseDouble(temp.getStartValue());

                                vals.addValue(temp.getName(), val);
                            }

                            try {
                                ans = expr.evaluateDouble(vals);
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                            pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));
                        }
                    }

                }

                if (isNewGraph) {
                    addGraph(graph);
                }
            } else {

                // this will always be a parametric graph for the 3d case
                ParametricGraph3D pGraph = (ParametricGraph3D) graph;

                //add the graph to the gui
                addGraph(pGraph);

                //Get the constants we want to put on the x and y axis
                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());
                ConstantLine yAxisConstant = constantList.getConstantLine(yAxis.getSelectedItem().toString());

                //add the single values to a global values list

                Values singleValuesGlobal = new Values();

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                pGraph.setGlobalValues(singleValuesGlobal);
                pGraph.setAxisConstants(xAxis.getSelectedItem().toString(), yAxis.getSelectedItem().toString());
                pGraph.setBounds(xAxisConstant.getStartValue(), xAxisConstant.getEndValue(),
                        yAxisConstant.getStartValue(), yAxisConstant.getEndValue());

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //plot the graph
                        pGraph.plot(expr.toString(), xAxis.getSelectedItem().toString(), "Function",
                                yAxis.getSelectedItem().toString());

                        //calculate the sampling rates from the step sizes as given by the user

                        int xSamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));
                        int ySamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));

                        pGraph.setSamplingRates(xSamples, ySamples);
                    }
                });

            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    //add everything to the dialog show the dialog

    dialog.add(exprPanel);
    dialog.add(axisPanel);
    dialog.add(constantPanel);
    dialog.add(bottomPanel);
    dialog.setVisible(true);

}

From source file:interfaces.InterfazPrincipal.java

private void TablaDeProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaDeProductosMouseClicked
    // TODO add your handling code here:
    int fila = TablaDeProductos.getSelectedRow();
    final int identificacion = (int) TablaDeProductos.getValueAt(fila, 1);

    final ControladorProducto controladorP = new ControladorProducto();
    ArrayList<Productos> listaProductos = controladorP.getProducto(" where producto_id = " + identificacion);
    final Productos productoActual = listaProductos.get(0);

    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Editar clientes");
    dialogoEditar.setSize(600, 310);// w w w . ja v  a2  s . c  o  m
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel editarTextoPrincipalDialogo = new JLabel("Editar producto");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    c.insets = new Insets(15, 200, 40, 0);
    c.ipadx = 100;
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 40;
    JLabel editarNombreClienteDialogo = new JLabel("Nombre:");
    panelDialogo.add(editarNombreClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);
    final JTextField valorEditarNombreClienteDialogo = new JTextField();
    valorEditarNombreClienteDialogo.setText(productoActual.getNombre());
    panelDialogo.add(valorEditarNombreClienteDialogo, c);

    final JTextField valorEditarUnidadesProductoDialogo = new JTextField();
    valorEditarUnidadesProductoDialogo.setText(String.valueOf(productoActual.getUnidadesDisponibles()));
    panelDialogo.add(valorEditarUnidadesProductoDialogo, c);

    c.gridx = 2;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 15, 10, 0);
    JLabel editarTelefonoClienteDialogo = new JLabel("Precio");
    panelDialogo.add(editarTelefonoClienteDialogo, c);

    c.gridx = 3;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 0, 10, 0);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 5, 10, 0);
    JLabel editarCelularClienteDialogo = new JLabel("Descripcion:");
    panelDialogo.add(editarCelularClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);

    final JTextField valorEditarDescripcionProductoDialogo = new JTextField();
    valorEditarDescripcionProductoDialogo.setText(productoActual.getDescripcion());
    panelDialogo.add(valorEditarDescripcionProductoDialogo, c);
    c.gridx = 2;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 5, 10, 0);
    JLabel editarMontoClienteDialogo = new JLabel("Unidades");
    panelDialogo.add(editarMontoClienteDialogo, c);

    c.gridx = 3;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);

    final JTextField valorEditarPrecioProductoDialogo = new JTextField();
    valorEditarPrecioProductoDialogo.setText(productoActual.getPrecio() + "");
    panelDialogo.add(valorEditarPrecioProductoDialogo, c);

    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 5, 10, 0);
    JLabel editarCodigoBarrasProyecto = new JLabel("Cdigo de barras:");
    panelDialogo.add(editarCodigoBarrasProyecto, c);

    c.gridx = 1;
    c.gridy = 3;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);

    final JTextField valorCodigoDeBarras = new JTextField();
    valorCodigoDeBarras.setText(productoActual.getCodigoBarras());
    panelDialogo.add(valorCodigoDeBarras, c);

    c.gridx = 0;
    c.gridy = 4;
    c.gridwidth = 2;
    c.ipadx = 100;
    c.insets = new Insets(15, 40, 0, 0);
    JButton botonGuardarProductoDialogo = new JButton("Guardar");
    panelDialogo.add(botonGuardarProductoDialogo, c);

    c.gridx = 2;
    c.gridy = 4;
    c.gridwidth = 2;
    c.insets = new Insets(15, 40, 0, 0);
    c.ipadx = 100;

    JButton botonCerrarProductoDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarProductoDialogo, c);

    dialogoEditar.add(panelDialogo);

    botonCerrarProductoDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarProductoDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                String[] selection = { "nombre", "descripcion", "unidades", "precio", "codigoBarras" };
                String[] value = { valorEditarNombreClienteDialogo.getText(),
                        valorEditarDescripcionProductoDialogo.getText(),
                        valorEditarUnidadesProductoDialogo.getText(),
                        valorEditarPrecioProductoDialogo.getText(), valorCodigoDeBarras.getText() };
                String[] type_value = { "varchar", "varchar", "int", "double", "varchar" };
                String restriction = " where producto_id = " + identificacion;
                controladorP.updateProduct(selection, value, type_value, restriction);
                JOptionPane.showMessageDialog(dialogoEditar, "Se ha editado el producto xitosamente");
                dialogoEditar.dispose();

                //Refrescar busqueda actual
                jButton2ActionPerformed(null);

            } catch (Exception event) {

                JOptionPane.showMessageDialog(dialogoEditar, "El valor del monto debe ser numrico");

            }

        }
    });

    dialogoEditar.setVisible(true);
}

From source file:interfaces.InterfazPrincipal.java

private void botonBuscarClienteCrearFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarClienteCrearFacturaActionPerformed

    String nombre = nombreClienteCrearFactura.getText();
    String identificacion = IdentificacionClienteBuscarFactura.getText();

    ControladorCliente controladorCliente = new ControladorCliente();

    try {//w ww .  ja va  2 s  .c  om
        int id = 0;
        if (!identificacion.equals("")) {
            id = Integer.parseInt(identificacion);
        }

        ArrayList<Cliente> listaClientes = controladorCliente.obtenerClientes(nombre, id);

        if (listaClientes.isEmpty()) {
            mensajesBusquedaClientesFactura.setText("La busqueda no arrojo resultados");
            return;
        }

        final JDialog dialogoEditar = new JDialog(this);
        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(600, 310);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 4;
        c.insets = new Insets(15, 200, 40, 0);
        c.ipadx = 100;
        Font textoGrande = new Font("Arial", 1, 18);
        editarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(editarTextoPrincipalDialogo, c);

        /*Vector col = new Vector();
         col.add("1");
         col.add("2");
         col.add("3");
         col.add("4");
         Vector row = new Vector();
                
         for (int i = 0; i < listaClientes.size(); i++) {
         Cliente cliente = listaClientes.get(i);
         Vector temp = new Vector();
         temp.add((i + 1) + "");
         temp.add(cliente.getNombre());
         temp.add(cliente.getCliente_id() + "");
         temp.add(cliente.getMonto_prestamo() + "");
         System.out.println("info" + cliente.getNombre() + "," + cliente.getMonto_prestamo());
         row.add(temp);
         }
                
         final JTable table = new JTable(row, col);         */
        final JTable table = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int column) {
                //all cells false
                return false;
            }
        };
        ;

        modeloTabla.addColumn("Numero");
        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");
        modeloTabla.addColumn("Monto Prestamo");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2", "3", "4" };
            data[0] = (i + 1);
            data[1] = listaClientes.get(i).getCliente_id();
            data[2] = listaClientes.get(i).getNombre();
            data[3] = listaClientes.get(i).getMonto_prestamo();

            modeloTabla.addRow(data);
        }

        table.setModel(modeloTabla);
        table.getColumn("Numero").setMinWidth(50);
        table.getColumn("Identificacin").setMinWidth(50);
        table.getColumn("Nombre").setMinWidth(110);
        table.getColumn("Monto Prestamo").setMinWidth(110);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setPreferredSize(new Dimension(320, 150));

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                String identificacion = table.getValueAt(table.getSelectedRow(), 3).toString();
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacion)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);
                    Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                }
                nombreClienteCrearFactura.setText(table.getValueAt(table.getSelectedRow(), 2).toString());
                IdentificacionClienteBuscarFactura
                        .setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                double montoPrestamo = Double
                        .parseDouble(table.getValueAt(table.getSelectedRow(), 3).toString());
                Double totalDisponible = montoPrestamo - pago;
                valorActualPrestamo.setText(String.valueOf(totalDisponible));
                //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
                botonAgregarProducto.setEnabled(true);
                botonGuardarFactura.setEnabled(true);
                botonEstablecerMontoFactura.setEnabled(true);
                dialogoEditar.dispose();
            }
        });

        c.insets = new Insets(0, 5, 10, 0);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 1;
        c.ipadx = 200;

        //panelDialogo.add(table, c);
        panelDialogo.add(scroll, c);
        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);
    } catch (Exception e) {
        mensajesBusquedaClientesFactura.setText("La identificacion debe ser un numero");

    }

}