Example usage for javax.swing JFrame setLocationRelativeTo

List of usage examples for javax.swing JFrame setLocationRelativeTo

Introduction

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

Prototype

public void setLocationRelativeTo(Component c) 

Source Link

Document

Sets the location of the window relative to the specified component according to the following scenarios.

Usage

From source file:com.mirth.connect.plugins.imageviewer.ImageViewer.java

public void viewAttachments(String channelId, Long messageId, String attachmentId) {

    JFrame frame = new JFrame("Image Viewer");

    try {/* ww w.  j a  va 2  s.c  om*/

        Attachment attachment = parent.mirthClient.getAttachment(channelId, messageId, attachmentId);
        byte[] rawData = attachment.getContent();
        ByteArrayInputStream bis = new ByteArrayInputStream(rawData);

        image = ImageIO.read(new Base64InputStream(bis));

        JScrollPane pictureScrollPane = new JScrollPane(new JLabel(new ImageIcon(image)));
        pictureScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pictureScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        frame.add(pictureScrollPane);

        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

        frame.pack();

        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // Resize the frame so that it fits and scrolls images larger than
        // 800x600 properly.
        if (imageWidth > 800 || imageHeight > 600) {
            int width = imageWidth;
            int height = imageHeight;
            if (imageWidth > 800) {
                width = 800;
            }
            if (imageHeight > 600) {
                height = 600;
            }

            // Also add the scrollbars to the window width if necessary.
            Integer scrollBarWidth = (Integer) UIManager.get("ScrollBar.width");
            int verticalScrollBar = 0;
            int horizontalScrollBar = 0;

            if (width == 800) {
                horizontalScrollBar = scrollBarWidth.intValue();
            }
            if (height == 600) {
                verticalScrollBar = scrollBarWidth.intValue();
            }

            // Also add the window borders to the width.
            width = width + frame.getInsets().left + frame.getInsets().right + verticalScrollBar;
            height = height + frame.getInsets().top + frame.getInsets().bottom + horizontalScrollBar;

            frame.setSize(width, height);
        }

        Dimension dlgSize = frame.getSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            frame.setLocationRelativeTo(null);
        } else {
            frame.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        frame.setVisible(true);
    } catch (Exception e) {
        parent.alertThrowable(parent, e);
    }
}

From source file:Assignment2.FarmManagementGUI.java

private void btnAirTempChartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAirTempChartActionPerformed
    //Set up chart data/key
    XYSeries signal = new XYSeries("amount");
    XYSeriesCollection dataset = new XYSeriesCollection(signal);

    JFrame f = new JFrame(selectedPlot.getName() + " air temperature chart"); //set up new JFrame
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //dispose frame on close
    JFreeChart chart = ChartFactory.createXYLineChart(selectedPlot.getName(), "Reading number", "Reading",
            dataset); //create chart and add data/keys
    f.add(new ChartPanel(chart)); //add chart to frame
    JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    signal.clear();//  www .j  a  va 2  s  .c  o m
    Sensor sensor;
    SensorData sensorData;
    //For each sensor in selected plot:
    for (int i = 0; i < selectedPlot.getSensors().size(); i++) {
        sensor = selectedPlot.getSensors().get(i);
        if (sensor.getSensorType() == SensorType.AIR_TEMPERATURE) {
            //For each sensor data in sensor:
            for (int j = 0; j < sensor.getSensorDataList().size(); j++) {
                sensorData = sensor.getSensorDataList().get(j);
                signal.add(j, sensorData.getDataRepresentationType()); //add the data to the chart
            }
        }
    }
    //set up frame and show:
    f.add(p, BorderLayout.SOUTH);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

From source file:es.emergya.ui.plugins.admin.AdminLayers.java

protected SummaryAction getSummaryAction(final CapaInformacion capaInformacion) {
    SummaryAction action = new SummaryAction(capaInformacion) {

        private static final long serialVersionUID = -3691171434904452485L;

        @Override//from   w ww . j  a v  a2s  .c o  m
        protected JFrame getSummaryDialog() {

            if (capaInformacion != null) {
                d = getDialog(capaInformacion, null, "", null, "image/png");
                return d;
            } else {
                JDialog primera = getJDialog();
                primera.setResizable(false);
                primera.setVisible(true);
                primera.setAlwaysOnTop(true);
            }
            return null;
        }

        private JDialog getJDialog() {
            final JDialog dialog = new JDialog();
            dialog.setTitle(i18n.getString("admin.capas.nueva.titleBar"));
            dialog.setIconImage(getBasicWindow().getIconImage());

            dialog.setLayout(new BorderLayout());

            JPanel centro = new JPanel(new FlowLayout());
            centro.setOpaque(false);
            JLabel label = new JLabel(i18n.getString("admin.capas.nueva.url"));
            final JTextField url = new JTextField(50);
            final JLabel icono = new JLabel(LogicConstants.getIcon("48x48_transparente"));
            label.setLabelFor(url);
            centro.add(label);
            centro.add(url);
            centro.add(icono);
            dialog.add(centro, BorderLayout.CENTER);

            JPanel pie = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            pie.setOpaque(false);
            final JButton siguiente = new JButton(i18n.getString("admin.capas.nueva.boton.siguiente"),
                    LogicConstants.getIcon("button_next"));
            JButton cancelar = new JButton(i18n.getString("admin.capas.nueva.boton.cancelar"),
                    LogicConstants.getIcon("button_cancel"));
            final SiguienteActionListener siguienteActionListener = new SiguienteActionListener(url, dialog,
                    icono, siguiente);
            url.addActionListener(siguienteActionListener);

            siguiente.addActionListener(siguienteActionListener);

            cancelar.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                }
            });
            pie.add(siguiente);
            pie.add(cancelar);
            dialog.add(pie, BorderLayout.SOUTH);

            dialog.getContentPane().setBackground(Color.WHITE);

            dialog.pack();
            dialog.setLocationRelativeTo(null);
            return dialog;
        }

        private JFrame getDialog(final CapaInformacion c, final Capa[] left_items, final String service,
                final Map<String, Boolean> transparentes, final String png) {

            if (left_items != null && left_items.length == 0) {
                JOptionPane.showMessageDialog(AdminLayers.this,
                        i18n.getString("admin.capas.nueva.error.noCapasEnServicio"));
            } else {

                final String label_cabecera = i18n.getString("admin.capas.nueva.nombreCapa");
                final String label_pie = i18n.getString("admin.capas.nueva.infoAdicional");
                final String centered_label = i18n.getString("admin.capas.nueva.origenDatos");
                final String left_label = i18n.getString("admin.capas.nueva.subcapasDisponibles");
                final String right_label;
                if (left_items != null) {
                    right_label = i18n.getString("admin.capas.nueva.capasSeleccionadas");
                } else {
                    right_label = i18n.getString("admin.capas.ficha.capasSeleccionadas");
                }
                final String tituloVentana, cabecera;
                if (c.getNombre() == null) {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.nuevaCapa");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.nuevaCapa");
                } else {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.ficha");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.ficha");
                }

                final Capa[] right_items = c.getCapas().toArray(new Capa[0]);
                final AdminPanel.SaveOrUpdateAction<CapaInformacion> guardar = layers.new SaveOrUpdateAction<CapaInformacion>(
                        c) {

                    private static final long serialVersionUID = 7447770296943341404L;

                    @Override
                    public void actionPerformed(ActionEvent e) {

                        if (isNew && CapaConsultas.alreadyExists(textfieldCabecera.getText())) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaYaExiste"));

                        } else if (textfieldCabecera.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaEnBlanco"));

                        } else if (((DefaultListModel) right.getModel()).size() == 0) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.noCapasSeleccionadas"));

                        } else if (cambios) {
                            int i = JOptionPane.showConfirmDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.confirmar.guardar.titulo"),
                                    i18n.getString("admin.capas.nueva.confirmar.boton.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                if (original == null) {
                                    original = new CapaInformacion();

                                }
                                original.setInfoAdicional(textfieldPie.getText());
                                original.setNombre(textfieldCabecera.getText());
                                original.setHabilitada(habilitado.isSelected());
                                original.setOpcional(comboTipoCapa.getSelectedIndex() != 0);

                                boolean transparente = true;

                                HashSet<Capa> capas = new HashSet<Capa>();
                                List<Capa> capasEnOrdenSeleccionado = new ArrayList<Capa>();
                                int indice = 0;
                                for (Object c : ((DefaultListModel) right.getModel()).toArray()) {
                                    if (c instanceof Capa) {
                                        transparente = transparente && (transparentes != null
                                                && transparentes.get(((Capa) c).getNombre()) != null
                                                && transparentes.get(((Capa) c).getNombre()));
                                        capas.add((Capa) c);
                                        capasEnOrdenSeleccionado.add((Capa) c);
                                        ((Capa) c).setCapaInformacion(original);
                                        ((Capa) c).setOrden(indice++);
                                        // ((Capa)
                                        // c).setNombre(c.toString());
                                    }

                                }
                                original.setCapas(capas);

                                if (original.getId() == null) {
                                    String url = nombre.getText();

                                    if (url.indexOf("?") > -1) {
                                        if (!url.endsWith("?")) {
                                            url += "&";

                                        }
                                    } else {
                                        url += "?";

                                    }
                                    url += "VERSION=" + version + "&REQUEST=GetMap&FORMAT=" + png + "&SERVICE="
                                            + service + "&WIDTH={2}&HEIGHT={3}&BBOX={1}&SRS={0}";
                                    // if (transparente)
                                    url += "&TRANSPARENT=TRUE";
                                    url += "&LAYERS=";

                                    String estilos = "";
                                    final String coma = "%2C";
                                    if (capasEnOrdenSeleccionado.size() > 0) {
                                        for (Capa c : capasEnOrdenSeleccionado) {
                                            url += c.getTitulo().replaceAll(" ", "+") + coma;
                                            estilos += c.getEstilo() + coma;
                                        }
                                        estilos = estilos.substring(0, estilos.length() - coma.length());

                                        estilos = estilos.replaceAll(" ", "+");

                                        url = url.substring(0, url.length() - coma.length());
                                    }
                                    url += "&STYLES=" + estilos;
                                    original.setUrl_visible(original.getUrl());
                                    original.setUrl(url);
                                }
                                CapaInformacionAdmin.saveOrUpdate(original);

                                cambios = false;

                                layers.setTableData(getAll(new CapaInformacion()));

                                closeFrame();
                            } else if (i == JOptionPane.NO_OPTION) {
                                closeFrame();

                            }
                        } else {
                            closeFrame();

                        }
                    }
                };
                JFrame segunda = generateUrlDialog(label_cabecera, label_pie, centered_label, tituloVentana,
                        left_items, right_items, left_label, right_label, guardar,
                        LogicConstants.getIcon("tittleficha_icon_capa"), cabecera, c.getHabilitada(),
                        c.getOpcional(), c.getUrl_visible());
                segunda.setResizable(false);

                if (c != null) {
                    textfieldCabecera.setText(c.getNombre());
                    textfieldPie.setText(c.getInfoAdicional());
                    nombre.setText(c.getUrl_visible());
                    nombre.setEditable(false);
                    if (c.getHabilitada() == null) {
                        c.setHabilitada(false);

                    }
                    habilitado.setSelected(c.getHabilitada());
                    if (c.isOpcional() != null && c.isOpcional()) {
                        comboTipoCapa.setSelectedIndex(1);
                    } else {
                        comboTipoCapa.setSelectedIndex(0);
                    }
                }

                if (c.getId() == null) {
                    habilitado.setSelected(true);
                    comboTipoCapa.setSelectedIndex(1);
                }

                habilitado.setEnabled(true);
                if (c == null || c.getId() == null) {
                    textfieldCabecera.setEditable(true);
                } else {
                    textfieldCabecera.setEditable(false);
                }

                cambios = false;

                segunda.pack();
                segunda.setLocationRelativeTo(null);
                segunda.setVisible(true);
                return segunda;
            }
            return null;
        }

        class SiguienteActionListener implements ActionListener {

            private final JTextField url;
            private final JDialog dialog;
            private final JLabel icono;
            private final JButton siguiente;

            public SiguienteActionListener(JTextField url, JDialog dialog, JLabel icono, JButton siguiente) {
                this.url = url;
                this.dialog = dialog;
                this.icono = icono;
                this.siguiente = siguiente;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                final CapaInformacion ci = new CapaInformacion();
                ci.setUrl(url.getText());
                ci.setCapas(new HashSet<Capa>());
                SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                    private List<Capa> res = new LinkedList<Capa>();
                    private String service = "WMS";
                    private String png = null;
                    private Map<String, Boolean> transparentes = new HashMap<String, Boolean>();
                    private ArrayList<String> errorStack = new ArrayList<String>();
                    private Boolean goOn = true;

                    @SuppressWarnings(value = "unchecked")
                    @Override
                    protected Object doInBackground() throws Exception {
                        try {
                            final String url2 = ci.getUrl();
                            WMSClient client = new WMSClient(url2);
                            client.connect(new ICancellable() {

                                @Override
                                public boolean isCanceled() {
                                    return false;
                                }

                                @Override
                                public Object getID() {
                                    return System.currentTimeMillis();
                                }
                            });

                            version = client.getVersion();

                            for (final String s : client.getLayerNames()) {
                                WMSLayer layer = client.getLayer(s);
                                // this.service =
                                // client.getServiceName();
                                final Vector allSrs = layer.getAllSrs();
                                boolean epsg = (allSrs != null) ? allSrs.contains("EPSG:4326") : false;
                                final Vector formats = client.getFormats();
                                if (formats.contains("image/png")) {
                                    png = "image/png";
                                } else if (formats.contains("IMAGE/PNG")) {
                                    png = "IMAGE/PNG";
                                } else if (formats.contains("png")) {
                                    png = "png";
                                } else if (formats.contains("PNG")) {
                                    png = "PNG";
                                }
                                boolean image = png != null;
                                if (png == null) {
                                    png = "IMAGE/PNG";
                                }
                                if (epsg && image) {
                                    boolean hasTransparency = layer.hasTransparency();
                                    this.transparentes.put(s, hasTransparency);
                                    Capa capa = new Capa();
                                    capa.setCapaInformacion(ci);
                                    if (layer.getStyles().size() > 0) {
                                        capa.setEstilo(((WMSStyle) layer.getStyles().get(0)).getName());
                                    }
                                    capa.setNombre(layer.getTitle());
                                    capa.setTitulo(s);
                                    res.add(capa);
                                    if (!hasTransparency) {
                                        errorStack.add(i18n.getString(Locale.ROOT,
                                                "admin.capas.nueva.error.capaNoTransparente",
                                                layer.getTitle()));
                                    }
                                } else {
                                    String error = "";
                                    // if (opaque)
                                    // error += "<li>Es opaca</li>";
                                    if (!image) {
                                        error += i18n.getString("admin.capas.nueva.error.formatoPNG");
                                    }
                                    if (!epsg) {
                                        error += i18n.getString("admin.capas.nueva.error.projeccion");
                                    }
                                    final String cadena = i18n.getString(Locale.ROOT,
                                            "admin.capas.nueva.error.errorCapa", new Object[] { s, error });
                                    errorStack.add(cadena);
                                }
                            }
                        } catch (final Throwable t) {
                            log.error("Error al parsear el WMS", t);
                            goOn = false;
                            icono.setIcon(LogicConstants.getIcon("48x48_transparente"));

                            JOptionPane.showMessageDialog(dialog,
                                    i18n.getString("admin.capas.nueva.error.errorParseoWMS"));

                            siguiente.setEnabled(true);
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        super.done();
                        if (goOn) {

                            dialog.dispose();
                            ci.setUrl_visible(ci.getUrl());
                            final JFrame frame = getDialog(ci, res.toArray(new Capa[0]), service, transparentes,
                                    png);
                            if (!errorStack.isEmpty()) {
                                String error = "<html>";
                                for (final String s : errorStack) {
                                    error += s + "<br/>";
                                }
                                error += "</html>";
                                final String errorString = error;
                                SwingUtilities.invokeLater(new Runnable() {

                                    @Override
                                    public void run() {
                                        JOptionPane.showMessageDialog(frame, errorString);
                                    }
                                });
                            }
                        }
                    }
                };
                sw.execute();
                icono.setIcon(LogicConstants.getIcon("anim_conectando"));
                icono.repaint();
                siguiente.setEnabled(false);
            }
        }
    };

    return action;
}

From source file:org.pf.midea.MainUI.java

private void showConstellationWindow(ConstellationPoint[] _map, String _name) {
    JFrame constellation = new JFrame(" ?? " + _name);
    constellation.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    XYSeriesCollection dots = new XYSeriesCollection();
    XYSeries series = new XYSeries(_name);
    JFreeChart chart = ChartFactory.createScatterPlot("", "I", "Q", dots, PlotOrientation.VERTICAL, false,
            false, false);//from  www .java 2s  . c o  m
    XYPlot xyPlot = chart.getXYPlot();
    CustomXYToolTipGenerator tooltipsGenerator = new CustomXYToolTipGenerator();
    ArrayList<String> tooltips = new ArrayList<>();
    for (ConstellationPoint ccp : _map) {
        double I = ccp.getI();
        double Q = ccp.getQ();
        series.add(I, Q);
        tooltips.add(ccp.getCode().getStringSequence());
    }
    tooltipsGenerator.addToolTipSeries(tooltips);
    xyPlot.getRenderer().setBaseToolTipGenerator(tooltipsGenerator);
    double maxX = StatisticsTools.round(Math.abs(series.getMaxX()), 3);
    double maxY = StatisticsTools.round(Math.abs(series.getMaxY()), 3);
    double minX = StatisticsTools.round(Math.abs(series.getMinX()), 3);
    double minY = StatisticsTools.round(Math.abs(series.getMinY()), 3);
    if (maxX != 0 || minX != 0) {
        double X = Math.max(minX, maxX);
        xyPlot.getDomainAxis().setRange(-1.1 * X, 1.1 * X);
    } else
        xyPlot.getDomainAxis().setRange(-1, 1);
    if (maxY != 0 || minY != 0) {
        double Y = Math.max(minY, maxY);
        xyPlot.getRangeAxis().setRange(-1.1 * Y, 1.1 * Y);
    } else
        xyPlot.getRangeAxis().setRange(-1, 1);
    dots.addSeries(series);

    xyPlot.setBackgroundPaint(Color.WHITE);
    xyPlot.setDomainGridlinePaint(Color.GRAY);
    xyPlot.setRangeGridlinePaint(Color.GRAY);
    xyPlot.getRenderer().setSeriesPaint(0, Color.BLACK);
    xyPlot.setDomainZeroBaselineVisible(true);
    xyPlot.setRangeZeroBaselineVisible(true);

    ChartPanel chartPanel = new ChartPanel(chart);
    JPanel nestedPanel = new JPanel();
    nestedPanel.add(chartPanel, new CellConstraints());
    constellation.add(nestedPanel);
    constellation.pack();
    constellation.setLocationRelativeTo(null);
    constellation.setResizable(false);
    constellation.setVisible(true);
}

From source file:org.owasp.benchmark.score.report.ScatterVulns.java

private JFreeChart display(String title, int height, String category, Set<Report> toolResults) {
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // averages//from w  w  w. j a v a 2 s  .co  m
    ArrayList<Double> averageFalseRates = new ArrayList<Double>();
    ArrayList<Double> averageTrueRates = new ArrayList<Double>();

    int commercialToolCount = 0;
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("Scores");

    for (Report toolReport : toolResults) {
        if (!toolReport.isCommercial()) {
            OverallResult overallResult = toolReport.getOverallResults().getResults(category);
            series.add(overallResult.falsePositiveRate * 100, overallResult.truePositiveRate * 100);
        }
    }

    for (Report toolReport : toolResults) {
        if (toolReport.isCommercial()) {
            OverallResult overallResult = toolReport.getOverallResults().getResults(category);
            if (!BenchmarkScore.showAveOnlyMode) {
                series.add(overallResult.falsePositiveRate * 100, overallResult.truePositiveRate * 100);
            }
            commercialToolCount++;
            averageFalseRates.add(overallResult.falsePositiveRate);
            averageTrueRates.add(overallResult.truePositiveRate);
        }
    }

    for (double d : averageFalseRates) {
        afr += d;
    }
    afr = afr / averageFalseRates.size();

    for (double d : averageTrueRates) {
        atr += d;
    }
    atr = atr / averageTrueRates.size();

    if (commercialToolCount > 1 || (BenchmarkScore.showAveOnlyMode && commercialToolCount == 1)) {
        series.add(afr * 100, atr * 100);
    }

    dataset.addSeries(series);

    chart = ChartFactory.createScatterPlot(title, "False Positive Rate", "True Positive Rate", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    theme.apply(chart);

    XYPlot xyplot = chart.getXYPlot();

    initializePlot(xyplot);

    makeDataLabels(category, toolResults, xyplot);
    makeLegend(category, toolResults, 103, 100.5, dataset, xyplot);

    for (XYDataItem item : (List<XYDataItem>) series.getItems()) {
        double x = item.getX().doubleValue();
        double y = item.getY().doubleValue();
        double z = (x + y) / 2;
        XYLineAnnotation score = new XYLineAnnotation(x, y, z, z, dashed, Color.blue);
        xyplot.addAnnotation(score);
    }

    ChartPanel cp = new ChartPanel(chart, height, height, 400, 400, 1200, 1200, false, false, false, false,
            false, false);
    f.add(cp);
    f.pack();
    f.setLocationRelativeTo(null);
    // f.setVisible(true);

    return chart;
}

From source file:org.owasp.benchmark.score.report.ScatterHome.java

private JFreeChart display(String title, int height, Set<Report> toolResults) {
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //averages//from w ww .  ja v a 2 s  .  co  m
    ArrayList<Double> averageCommercialFalseRates = new ArrayList<Double>();
    ArrayList<Double> averageCommercialTrueRates = new ArrayList<Double>();

    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("Scores");
    for (Report toolReport : toolResults) {
        if (!toolReport.isCommercial()) {
            OverallResults overallResults = toolReport.getOverallResults();
            series.add(overallResults.getFalsePositiveRate() * 100, overallResults.getTruePositiveRate() * 100);
            if (toolReport.isCommercial()) {
                averageCommercialFalseRates.add(overallResults.getFalsePositiveRate());
                averageCommercialTrueRates.add(overallResults.getTruePositiveRate());
            }
        }
    }

    int commercialToolCount = 0;
    for (Report toolReport : toolResults) {
        if (toolReport.isCommercial()) {
            commercialToolCount++;
            OverallResults overallResults = toolReport.getOverallResults();
            if (!BenchmarkScore.showAveOnlyMode) {
                series.add(overallResults.getFalsePositiveRate() * 100,
                        overallResults.getTruePositiveRate() * 100);
            }
            if (toolReport.isCommercial()) {
                averageCommercialFalseRates.add(overallResults.getFalsePositiveRate());
                averageCommercialTrueRates.add(overallResults.getTruePositiveRate());
            }
        }
    }

    for (double d : averageCommercialFalseRates) {
        afr += d;
    }
    afr = afr / averageCommercialFalseRates.size();

    for (double d : averageCommercialTrueRates) {
        atr += d;
    }
    atr = atr / averageCommercialTrueRates.size();

    if (commercialToolCount > 1 || (BenchmarkScore.showAveOnlyMode && commercialToolCount == 1)) {
        series.add(afr * 100, atr * 100);
    }

    dataset.addSeries(series);

    chart = ChartFactory.createScatterPlot(title, "False Positive Rate", "True Positive Rate", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    theme.apply(chart);

    XYPlot xyplot = chart.getXYPlot();
    initializePlot(xyplot);

    makeDataLabels(toolResults, xyplot);
    makeLegend(toolResults, 103, 100.5, dataset, xyplot);

    for (XYDataItem item : (List<XYDataItem>) series.getItems()) {
        double x = item.getX().doubleValue();
        double y = item.getY().doubleValue();
        double z = (x + y) / 2;
        XYLineAnnotation score = new XYLineAnnotation(x, y, z, z, dashed, Color.blue);
        xyplot.addAnnotation(score);
    }

    ChartPanel cp = new ChartPanel(chart, height, height, 400, 400, 1200, 1200, false, false, false, false,
            false, false);
    f.add(cp);
    f.pack();
    f.setLocationRelativeTo(null);
    //      f.setVisible(true);
    return chart;
}

From source file:com.diversityarrays.kdxplore.curate.TrialDataEditor.java

private JFrame addGraphOrPlotPanel(DesktopObject dobj) {
    JFrame frame = windowOpener.addDesktopObject(dobj);
    JMenuBar mbar = new JMenuBar();
    frame.setJMenuBar(getJMenuBar());//from  w  w  w. j  a v  a 2  s .c  om
    toolFrames.add(frame);

    frame.addWindowListener(plotTitleUncounter);

    Dimension size = this.getSize();
    size.width = Math.max(size.width / 2, 640);
    size.height = Math.max(size.height / 2, 640);
    frame.setSize(size);
    frame.setLocationRelativeTo(null);

    windowsMenuManager.addWindow(frame, dobj.getTitle());
    refreshToolAll();
    return frame;
}

From source file:org.pf.midea.MainUI.java

private void menuItemAboutActionPerformed(ActionEvent e) {
    JFrame about = new JFrame(" ");
    about.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    JPanel nestedPanel = new JPanel();
    nestedPanel.setLayout(new GridLayout(17, 1));
    nestedPanel/*from   www .j a  v  a 2s  .  c  o  m*/
            .add(new JLabel("? ? ?"));
    nestedPanel.add(new JLabel("?  ?"));
    nestedPanel.add(new JLabel("  ?"));
    nestedPanel.add(new JLabel(""));
    nestedPanel.add(new JLabel(" . . ?, 20072013"));
    nestedPanel.add(new JLabel(" ?  ? "));
    nestedPanel.add(new JLabel(""));
    nestedPanel.add(new JLabel("   ???"));
    nestedPanel.add(new JLabel(
            "   ?   ? 4.2."));
    nestedPanel.add(new JLabel(
            "   ?  ??"));
    nestedPanel.add(new JLabel("  COPYING (???  )."));
    nestedPanel.add(new JLabel(""));
    nestedPanel.add(new JLabel(
            "?  ? ??  ?:"));
    JLabel labelMail = new JLabel(
            "<html><a href=\"mailto:oleksandr@natalenko.name\">oleksandr@natalenko.name</a></html>");
    labelMail.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            try {
                Desktop.getDesktop()
                        .mail(new URI("mailto:oleksandr@natalenko.name?subject=" + URLEncoder.encode(
                                "? ? ?",
                                "UTF-8")));
            } catch (URISyntaxException | IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    nestedPanel.add(labelMail);
    nestedPanel.add(new JLabel(""));
    nestedPanel.add(new JLabel("-? :"));
    JLabel labelURL = new JLabel("<html><a href=\"http://natalenko.name/\">http://natalenko.name/</a></html>");
    labelURL.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("http://natalenko.name/"));
            } catch (URISyntaxException | IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    nestedPanel.add(labelURL);
    about.add(nestedPanel);
    about.pack();
    about.setLocationRelativeTo(null);
    about.setVisible(true);
}

From source file:com.pianobakery.complsa.MainGui.java

public void createNewProjectFolder() {

    try {/* w ww . j  av  a  2 s. c o  m*/
        JFrame frame = new JFrame();
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(openFolder);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
        chooser.setDialogTitle("Create Folder");
        chooser.setFileHidingEnabled(Boolean.TRUE);
        chooser.setMultiSelectionEnabled(false);
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setSelectedFile(new File("Workingfile"));
        frame.getContentPane().add(chooser);
        chooser.setApproveButtonText("Choose");

        //Disable Save as
        ArrayList<JPanel> jpanels = new ArrayList<JPanel>();
        for (Component c : chooser.getComponents()) {
            if (c instanceof JPanel) {
                jpanels.add((JPanel) c);
            }

        }
        jpanels.get(0).getComponent(0).setVisible(false);
        frame.pack();
        frame.setLocationRelativeTo(null);

        int whatChoose = chooser.showSaveDialog(null);
        if (whatChoose == JFileChooser.APPROVE_OPTION) {
            File selFile = chooser.getSelectedFile();
            File currDir = chooser.getCurrentDirectory();
            Path parentDir = Paths.get(chooser.getCurrentDirectory().getParent());
            String parentDirName = parentDir.getFileName().toString();

            logger.debug("Chooser SelectedFile: " + selFile.toString());
            logger.debug("getCurrentDirectory(): " + currDir.toString());
            logger.debug("Chooser parentdir: " + parentDir);
            logger.debug("Parentdirname: " + parentDirName);

            if (selFile.getName().equals(parentDirName)) {
                wDir = currDir;
            } else {
                wDir = chooser.getSelectedFile();
            }

            logger.debug("WDIR is: " + wDir.toString());
            wDirText.setText(wDir.toString());
            enableUIElements(true);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Falsche Eingabe");
        logger.debug("Exeption: " + ex.toString());
    }
}

From source file:org.owasp.benchmark.score.report.Scatter.java

private JFreeChart display(String title, int height, int width, OverallResults or) {
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Note: this is a little weird, since each point is a separate series
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("Scores");
    for (OverallResult r : or.getResults()) {
        series.add(r.fpr * 100, r.tpr * 100);
    }/*from  ww  w . j av a  2  s  . co  m*/
    dataset.addSeries(series);

    chart = ChartFactory.createScatterPlot(title, "False Positive Rate", "True Positive Rate", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    String fontName = "Arial";
    DecimalFormat pctFormat = new DecimalFormat("0'%'");

    theme = (StandardChartTheme) org.jfree.chart.StandardChartTheme.createJFreeTheme();
    theme.setExtraLargeFont(new Font(fontName, Font.PLAIN, 24)); // title
    theme.setLargeFont(new Font(fontName, Font.PLAIN, 20)); // axis-title
    theme.setRegularFont(new Font(fontName, Font.PLAIN, 16));
    theme.setSmallFont(new Font(fontName, Font.PLAIN, 12));
    theme.setRangeGridlinePaint(Color.decode("#C0C0C0"));
    theme.setPlotBackgroundPaint(Color.white);
    theme.setChartBackgroundPaint(Color.white);
    theme.setGridBandPaint(Color.red);
    theme.setAxisOffset(new RectangleInsets(0, 0, 0, 0));
    theme.setBarPainter(new StandardBarPainter());
    theme.setAxisLabelPaint(Color.decode("#666666"));
    theme.apply(chart);

    XYPlot xyplot = chart.getXYPlot();
    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    NumberAxis domainAxis = (NumberAxis) xyplot.getDomainAxis();

    xyplot.setOutlineVisible(true);

    rangeAxis.setRange(-9.99, 109.99);
    rangeAxis.setNumberFormatOverride(pctFormat);
    rangeAxis.setTickLabelPaint(Color.decode("#666666"));
    rangeAxis.setMinorTickCount(5);
    rangeAxis.setTickUnit(new NumberTickUnit(10));
    rangeAxis.setAxisLineVisible(true);
    rangeAxis.setMinorTickMarksVisible(true);
    rangeAxis.setTickMarksVisible(true);
    rangeAxis.setLowerMargin(10);
    rangeAxis.setUpperMargin(10);
    xyplot.setRangeGridlineStroke(new BasicStroke());
    xyplot.setRangeGridlinePaint(Color.lightGray);
    xyplot.setRangeMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setRangeMinorGridlinesVisible(true);

    domainAxis.setRange(-5, 105);
    domainAxis.setNumberFormatOverride(pctFormat);
    domainAxis.setTickLabelPaint(Color.decode("#666666"));
    domainAxis.setMinorTickCount(5);
    domainAxis.setTickUnit(new NumberTickUnit(10));
    domainAxis.setAxisLineVisible(true);
    domainAxis.setTickMarksVisible(true);
    domainAxis.setMinorTickMarksVisible(true);
    domainAxis.setLowerMargin(10);
    domainAxis.setUpperMargin(10);
    xyplot.setDomainGridlineStroke(new BasicStroke());
    xyplot.setDomainGridlinePaint(Color.lightGray);
    xyplot.setDomainMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setDomainMinorGridlinesVisible(true);

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    chart.removeLegend();
    chart.setPadding(new RectangleInsets(20, 20, 20, 20));
    xyplot.getRenderer().setSeriesPaint(0, Color.decode("#4572a7"));

    //        // setup item labels
    //        XYItemRenderer renderer = xyplot.getRenderer();
    //        Shape circle = new Ellipse2D.Float(-2.0f, -2.0f, 7.0f, 7.0f);
    //        for ( int i = 0; i < dataset.getSeriesCount(); i++ ) {
    //            renderer.setSeriesShape(i, circle);
    //            renderer.setSeriesPaint(i, Color.blue);
    //            String letter = "" + ((String)dataset.getSeries(i).getKey()).charAt(0);
    //            StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator(letter); 
    //            renderer.setSeriesItemLabelGenerator(i, generator); 
    //            renderer.setSeriesItemLabelsVisible(i, true);
    //            ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER );
    //            renderer.setSeriesPositiveItemLabelPosition(i, position);
    //        }

    makeDataLabels(or, xyplot);
    makeLegend(or, 57, 48, dataset, xyplot);

    // put legend inside plot
    //        LegendTitle lt = new LegendTitle(xyplot);
    //        lt.setItemFont(theme.getSmallFont());
    //        lt.setPosition(RectangleEdge.RIGHT);
    //        lt.setItemFont(theme.getSmallFont());
    //        XYTitleAnnotation ta = new XYTitleAnnotation(.7, .55, lt, RectangleAnchor.TOP_LEFT);
    //        ta.setMaxWidth(0.48);
    //        xyplot.addAnnotation(ta);

    // draw guessing line
    Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 6, 3 },
            0);
    XYLineAnnotation guessing = new XYLineAnnotation(-5, -5, 105, 105, dashed, Color.red);
    xyplot.addAnnotation(guessing);

    XYPointerAnnotation worse = makePointer(75, 0, "Worse than guessing", TextAnchor.TOP_CENTER, 90);
    xyplot.addAnnotation(worse);

    XYPointerAnnotation better = makePointer(25, 100, "Better than guessing", TextAnchor.BOTTOM_CENTER, 270);
    xyplot.addAnnotation(better);

    XYTextAnnotation time = new XYTextAnnotation("Tool run time: " + or.getTime(), 12, -5.6);
    time.setTextAnchor(TextAnchor.TOP_LEFT);
    time.setFont(theme.getRegularFont());
    time.setPaint(Color.red);
    xyplot.addAnnotation(time);

    XYTextAnnotation stroketext = new XYTextAnnotation("                     Random Guess", 88, 107);
    stroketext.setTextAnchor(TextAnchor.CENTER_RIGHT);
    stroketext.setBackgroundPaint(Color.white);
    stroketext.setPaint(Color.red);
    stroketext.setFont(theme.getRegularFont());
    xyplot.addAnnotation(stroketext);

    XYLineAnnotation strokekey = new XYLineAnnotation(58, 107, 68, 107, dashed, Color.red);
    xyplot.setBackgroundPaint(Color.white);
    xyplot.addAnnotation(strokekey);

    ChartPanel cp = new ChartPanel(chart, height, width, 400, 400, 1200, 1200, false, false, false, false,
            false, false);
    f.add(cp);
    f.pack();
    f.setLocationRelativeTo(null);
    //      f.setVisible(true);
    return chart;
}